[英]node.js + mongoose + HTTP PUT Not Working
我正在关注scotch的教程,所以我有以下用户模式:
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
}
});
我正在尝试放置一个http,以使用x-www-form-urlencoded更新一些数据,但是我无法设置字段,这就是我所拥有的:
PUT /teacherup HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
email=example%40gmail.com&password=randompass
如何制作适当的http放置并设置这些字段? 我也想知道如何使用JSON。
-用put更新
这是http放置:
app.put('/teacherup', isLoggedIn, function(req, res) {
if(req.user.usertype == 1)
{
util.updateDocument(req.user, userschema, req.body);
req.user.save(function(err) {
if (err)
throw err;
});
res.send(200, {message : 'Teacher saved!'});
}
else
{
res.send(406, {message : 'Not a teacher!'});
}
});
-保存文档的更新方法
我正在使用这些方法来更新文档
exports.updateDocument = function(doc, SchemaTarget, data) {
for (var field in SchemaTarget.schema.paths) {
if ((field !== '_id') && (field !== '__v')) {
var newValue = getObjValue(field, data);
console.log('data[' + field + '] = ' + newValue);
if (newValue !== undefined) {
setObjValue(field, doc, newValue);
}
}
}
return doc;
};
function getObjValue(field, data) {
return _.reduce(field.split("."), function(obj, f) {
if(obj) return obj[f];
}, data);
}
function setObjValue(field, data, value) {
var fieldArr = field.split('.');
return _.reduce(fieldArr, function(o, f, i) {
if(i == fieldArr.length-1) {
o[f] = value;
} else {
if(!o[f]) o[f] = {};
}
return o[f];
}, data);
}
我正在向您展示使用'express'和'mongoose'插入新文档的服务器端代码。 希望这对您有帮助。
var app = require('express)(),
mongoose=require('mongoose'),
userModel=mongoose.model("user", userSchema);
app.put('/teacherup', update);
update=function(req,res){
new userModel
.save(object)//I have not created the object you have to create it according to yourschema
.exec(function(err, result) {
if (err) {
console.log(err);
} else {
console.log("Successfully inserted");
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.