猫鼬findByIdAndUpdate没有返回正确的模型 [英] Mongoose findByIdAndUpdate not returning correct model

查看:107
本文介绍了猫鼬findByIdAndUpdate没有返回正确的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个以前从未见过的问题,即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);
    });

数据库中的原始文档如下:

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(和findOneAndUpdate)的new选项的默认值已更改为false(请参阅#2262) 发行说明).这意味着在应用更新后,您需要将选项显式设置为true以获得新版本的文档:

In Mongoose 4.0, the default value for the new option 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 true to get the new version of the doc, after the update is applied:

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

这篇关于猫鼬findByIdAndUpdate没有返回正确的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆