下面是我的代码

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它的第一时间得到原始数据。


当前回答

在某些情况下,{new: true}不起作用。 那你可以试试这个。

{'returnNewDocument':true}

其他回答

我是猫鼬的维护者。您需要将新选项设置为true(或等效地将returnorigoriginal设置为false)

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

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

请参阅Mongoose findOneAndUpdate()文档和在Mongoose中更新文档的教程。

此选项对于获取更新的文档实例是必需的

{ new: true }
const updatedDocument = await Model.findOneAndUpdate(req.params.id, req.body, {
    upsert: true,
    new: true,
  })

使用这个来获取更新文档

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

MongoDB shell

{returnNewDocument:真}

裁判:https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

猫鼬

{新:真}

裁判:http://mongoosejs.com/docs/api.html # query_Query-findOneAndUpdate

MongoDB Driver API:

{returnOriginal:假}

2021年- Mongodb ^4.2.0更新 {returnDocument: 'after'}

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

对于那些使用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 */ }