【发布时间】:2015-01-06 17:03:55
【问题描述】:
我正在关注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
}
});
我正在尝试创建一个 http put 以使用 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 put 并设置这些字段?我也想知道如何使用 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);
}
【问题讨论】:
-
大不了。控制器代码在哪里?
-
刚刚更新了 http put
-
与 Rep 分数无关。只是问题的质量。
req.params是所有 Web 框架中的一种标准。您甚至从未在网上搜索过“快速请求参数”吗?当您提出要求时,您应该期望老板会做出这种回应。 -
您要更新之前的文档还是保存当前文档?如果您清除了这一点,我会尽力帮助您。
-
我正在尝试更新以前的文档,只是用我使用的方法进行了更新
标签: node.js mongodb http mongoose