我正在关注scotch's教程,所以我有这个用户架构:
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
}
});
我试图使用x-www-form-urlencoded来设置http更新一些数据,但是我无法设置字段,这就是我所拥有的:
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 put:
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);
}
答案 0 :(得分:0)
我正在向您展示使用' 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");
}
});
}