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

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:

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

The updateObj going in looks like this:

{
    _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.

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

推荐答案

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) {...

Node.js相关问答推荐

使用NodeJS在S3上传文件时的格式问题

无法生成仅具有生产依赖项的 node 类型脚本项目

如何发送比特币BTC使用发送加密使用WIF密钥在 node ,js

在 NodeJS 中使用 post 时出现错误 500TypeError: 无法解构 'req.body' 的属性 'name',因为它未定义

将 null 推入管道后,node.js 可写完成未发出

为什么运行 yarn 命令会出错 - yargs-parser的完整性判断失败

MongoDB - 查找查询以判断是否存在少量字段,结合字段上的 AND

从 Response.json() 返回的 JSON 似乎无效?

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

在mongodb中只查询整数

mongoose.model() 方法返回未定义

Mongodb聚合传递一个匹配的数组和一个不匹配的数组

node.js 中 res.setHeader 和 res.header 的区别

如何使用适用于 Node.js 的 AWS 开发工具包将 Amazon S3 中的所有对象从一个前缀复制/移动到另一个前缀

在 Mongoose 中创建外键关系

Nodejs 随机免费 tcp 端口

如何在 MongoDB 上只收听 localhost

npm package.json 操作系统特定脚本

npm install 给出警告,npm audit fix 不起作用

我可以让 node --inspect 自动打开 Chrome