猫鼬:findOneAndUpdate不返回更新的文档

node.js Node.js

西里神奇

2020-03-23

下面是我的代码

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', {
    name: String,
    age: {type: Number, default: 20},
    create: {type: Date, default: Date.now} 
});

Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){
    if(err){
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

我的mongo数据库中已经有一些记录,我想运行此代码来更新年龄为17岁的姓名,然后在代码末尾打印结果。

但是,为什么我仍然从控制台获得相同的结果(而不是修改后的名称),但是当我转到mongo db命令行并键入“ db.cats.find();”时。结果带有修改后的名称。

然后,我再次运行该代码,并修改了结果。

我的问题是:如果修改了数据,那么为什么当console.log记录时我还是第一次得到原始数据。

第2579篇《猫鼬:findOneAndUpdate不返回更新的文档》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
西门 2020.03.23

猫鼬维护者在这里。您需要将new选项设置true(或等效地,设置returnOriginalfalse

await User.findOneAndUpdate(filter, update, { new: true });

// Equivalent
await User.findOneAndUpdate(filter, update, { returnOriginal: false });

请参阅Mongoose findOneAndUpdate()文档有关在Mongoose中更新文档的本教程

Harry神奇路易 2020.03.23

因此,“ findOneAndUpdate”需要一个选项来返回原始文档。并且,选项是:

MongoDB外壳

{returnNewDocument: true}

参考:https : //docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

猫鼬

{new: true}

参考:http : //mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate

Node.js MongoDB驱动程序API:

{returnOriginal: false}

参考:http : //mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#findOneAndUpdate

猪猪 2020.03.23

对于使用Node.js驱动程序而不是Mongoose的任何人,您都想使用{returnOriginal:false}而不是{new:true}

达蒙前端Green 2020.03.23

对于使用原生承诺的ES6 / ES7样式偶然发现此问题的人,可以采用以下模式...

const user = { id: 1, name: "Fart Face 3rd"};
const userUpdate = { name: "Pizza Face" };

try {
    user = await new Promise( ( resolve, reject ) => {
        User.update( { _id: user.id }, userUpdate, { upsert: true, new: true }, ( error, obj ) => {
            if( error ) {
                console.error( JSON.stringify( error ) );
                return reject( error );
            }

            resolve( obj );
        });
    })
} catch( error ) { /* set the world on fire */ }
斯丁 2020.03.23

为什么会这样?

默认情况下是返回原来的,不变的文件。如果要返回新的,更新的文档,则必须传递一个附加参数:new属性设置为的对象true

猫鼬文档中

Query#findOneAndUpdate

Model.findOneAndUpdate(conditions, update, options, (error, doc) => {
  // error: any errors that occurred
  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
});

可用选项

  • new:bool-如果为true,则返回修改后的文档而不是原始文档。默认为false(在4.0中更改)

传递{new: true}如果你想更新的结果的doc变量:

//                                                         V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});
卡卡西 2020.03.23

默认情况下,findOneAndUpdate返回原始文档。如果希望它返回修改后的文档{ new: true },则向该函数传递一个options对象

Cat.findOneAndUpdate({ age: 17 }, { $set: { name: "Naomi" } }, { new: true }, function(err, doc) {

});
猴子 2020.03.23

这是的更新代码findOneAndUpdate有用。

db.collection.findOneAndUpdate(    
  { age: 17 },      
  { $set: { name: "Naomi" } },      
  {
     returnNewDocument: true
  }    
)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android