下面是我的代码

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


当前回答

下面显示了查询mongoose的findOneAndUpdate。这里new: true用于获取更新的文档,fields用于获取特定的字段。

如。findOneAndUpdate(条件,更新,选项,回调)

await User.findOneAndUpdate({
      "_id": data.id,
    }, { $set: { name: "Amar", designation: "Software Developer" } }, {
      new: true,
      fields: {
        'name': 1,
        'designation': 1
      }
    }).exec();

其他回答

export function newDocumentOnUpdatePlugin(schema) {
  schema.pre(
    ['update', 'findOneAndUpdate', 'updateOne', 'updateMany'],
    function (next) {
      this.setOptions({ new: true });
      next();
    },
  );
}

我已经创建了这个插件,如果有人需要整个应用程序的这个功能,想要避免重复。只要把它作为一个全局插件使用

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

使用这个来获取更新文档

2021年- Mongodb ^4.2.0更新

适用于mongodb节点驱动,不适用于mongoose节点驱动。

如果你使用"collection.findOneAndUpdate"进行搜索和更新,最新版本的Mongodb节点驱动程序似乎使用了以下语法:

.findOneAndUpdate(query, update, { returnDocument: 'after' | 'before' })

我自己在搜索的时候找不到答案,所以把这个贴出来以防别人也有同样的情况。

对于任何使用Node.js驱动而不是Mongoose的人,你会想要使用{returnorigoriginal:false}而不是{new:true}。

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

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