Mongoose findByIdAndUpdate 没有在回调中返回正确的模型,这是我以前从未见过的问题。
代码如下:
var id = args._id;
var updateObj = {updatedDate: Date.now()};
_.extend(updateObj, args);
Model.findByIdAndUpdate(id, updateObj, function(err, model) {
if (err) {
logger.error(modelString +':edit' + modelString +' - ' + err.message);
self.emit('item:failure', 'Failed to edit ' + modelString);
return;
}
self.emit('item:success', model);
});
db中的原始文档是这样的:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 1'
}
进入的updateObj如下所示:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 2'
}
回调返回的模型与原始模型相同,而不是更新的Obj。 如果我查询数据库,它已正确更新。它只是没有从数据库中返回。
这感觉像是一个“愚蠢的用户”错误,但我看不到。任何想法都非常感谢。
最佳答案
在 Mongoose 4.0 中,findByIdAndUpdate
(和 findOneAndUpdate
)的 new
选项的默认值已更改为 false
,这意味着返回旧文档(参见 release notes 的 #2262)。因此,您需要在应用更新后将选项显式设置为 true
以获取新版本的文档:
Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...
关于node.js - Mongoose findByIdAndUpdate 没有返回正确的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419575/
相关文章:
java - Spring Data 的 MongoTemplate 和 MongoReposito
MongoDB select count(distinct x) on an indexed col
mongodb - 在 Mongoose/MongoDB 中创建多字段索引
node.js - 如何在 mongodb-native findOne() 中使用变量作为字段名?
mongodb - 无法验证到 mongo, "auth fails"
mongodb - Meteor 应用程序 — 重置已部署应用程序的数据库