我在使用 Mongoose 从查找中更新文档时遇到问题。问题仅在我尝试用对象覆盖文档时出现(例如 doc = req.body)。但是,我可以直接将原始文档的属性设置为特定字符串(例如 doc.name = 'jason borne';)。
我已经验证过 res.body 是一个对象,所以我不明白为什么我不能这样设置它。
Client.findById(req.params.client_id, function (err, client) {
if (err)
return next(new restify.InternalError(err));
// client.name = 'jason borne';
client = req.body;
client.save(function(err) {
if (err)
return next(new restify.InternalError(err));
res.send(client);
});
});
当尝试将文档设置为对象时,我收到错误:
TypeError: Object # has no method 'save'
我知道我可以使用简单的 Client.update(...) 命令进行更新,但是此方法不允许我的模式中间件或验证运行(在 Mongoose documentation 中注明)。
有什么想法吗?我是 Node 和 Mongoose 的新手。
最佳答案
你需要使用类似下划线的 extend
方法将 req.body
的属性复制到 client
对象中,而不是仅仅将 client
重新指向 req.body
和现在一样。
var _ = require('underscore');
Client.findById(req.params.client_id, function (err, client) {
if (err)
return next(new restify.InternalError(err));
_.extend(client, req.body);
client.save(function(err) {
if (err)
return next(new restify.InternalError(err));
res.send(client);
});
});
关于javascript - 在查找中更新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14346468/