Mongoose findByIdAndUpdate 没有返回正确的模型 [英] Mongoose findByIdAndUpdate not returning correct model
问题描述
我遇到了以前从未见过的问题,Mongoose findByIdAndUpdate 没有在回调中返回正确的模型.
I have an issue I've not seen before with the Mongoose findByIdAndUpdate not returning the correct model in the callback.
代码如下:
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 中的原始文档是这样的:
The original document in the db looks like this:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 1'
}
进入的 updateObj 看起来像这样:
The updateObj going in looks like this:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 2'
}
回调返回的模型与原始模型相同,而不是updatedObj.如果我查询数据库,它已被正确更新.它只是没有从数据库中返回.
The model returned from the callback is identical to the original model, not the updatedObj. If I query the db, it has been updated correctly. It's just not being returned from the database.
这感觉像是一个愚蠢的用户"错误,但我看不到.任何想法都非常感谢.
This feels like a 'stupid-user' error, but I can't see it. Any ideas greatly appreciated.
推荐答案
在 Mongoose 4.0 中,findByIdAndUpdate
的 new
选项的默认值(和 findOneAndUpdate
) 已更改为 false
,这意味着返回旧文档(请参阅 发行说明).因此,在应用更新后,您需要将选项显式设置为 true
以获取文档的新版本:
In Mongoose 4.0, the default value for the new
option of findByIdAndUpdate
(and findOneAndUpdate
) has changed to false
, which means returning the old doc (see #2262 of the release notes). So you need to explicitly set the option to true
to get the new version of the doc, after the update is applied:
Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...
这篇关于Mongoose findByIdAndUpdate 没有返回正确的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!