node.js Mongoose findByIdAndUpdate 没有返回正确的模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30419575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:47:26  来源:igfitidea点击:

Mongoose findByIdAndUpdate not returning correct model

node.jsmongodbmongoose

提问by JonRed

I have an issue I've not seen before with the Mongoose findByIdAndUpdate not returning the correct model in the callback.

我有一个以前从未见过的问题,Mongoose findByIdAndUpdate 没有在回调中返回正确的模型。

Here's the code:

这是代码:

    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);
    });

The original document in the db looks like this:

db 中的原始文档如下所示:

{
    _id: 1234
    descriptors: Array[2],
    name: 'Test Name 1'
}

The updateObj going in looks like this:

进入的 updateObj 如下所示:

{
    _id: 1234
    descriptors: Array[2],
    name: 'Test Name 2'
}  

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.

从回调返回的模型与原始模型相同,而不是 updatedObj。如果我查询数据库,它已被正确更新。它只是没有从数据库中返回。

This feels like a 'stupid-user' error, but I can't see it. Any ideas greatly appreciated.

这感觉像是一个“愚蠢的用户”错误,但我看不到。任何想法都非常感谢。

回答by JohnnyHK

In Mongoose 4.0, the default value for the newoption of findByIdAndUpdate(and findOneAndUpdate) has changed to false(see #2262 of the release notes). This means that you need to explicitly set the option to trueto get the new version of the doc, after the update is applied:

在 Mongoose 4.0 中,(and )new选项的默认值已更改为(请参阅发行说明的#2262 )。这意味着您需要在应用更新后显式设置选项以获取文档的新版本:findByIdAndUpdatefindOneAndUpdatefalsetrue

Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...