首页 文章

Mongoose:findOneAndUpdate不返回更新的文档

提问于
浏览
171

以下是我的代码

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时仍然获得了原始数据 .

7 回答

  • 11

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

    MongoDB shell

    {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

  • 22

    default 将返回 original, unaltered 文档 . 如果要返回新的更新文档,则必须传递一个附加参数: new 属性设置为 true 的对象 .

    来自mongoose docs

    查询#findOneAndUpdate Model.findOneAndUpdate(条件,更新,选项,(错误,doc)=> {
    //错误:发生的任何错误
    // doc:如果new:false应用更新之前的文档,或者如果new = true则更新之后应用更新之前的文档
    });
    可用选项new:bool - 如果为true,则返回修改后的文档而不是原始文档 . 默认为false(在4.0中更改)

    因此,如果您想要 doc 变量中的更新结果:

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

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

  • 0

    如果要返回更改的文档,则需要设置选项 {new:true} API参考,您可以使用 Cat.findOneAndUpdate(conditions, update, options, callback) // executes

    由Mongoose API http://mongoosejs.com/docs/api.html#findoneandupdate_findOneAndUpdate官方提供,您可以使用以下参数

    A.findOneAndUpdate(conditions, update, options, callback) // executes
    A.findOneAndUpdate(conditions, update, options)  // returns Query
    A.findOneAndUpdate(conditions, update, callback) // executes
    A.findOneAndUpdate(conditions, update)           // returns Query
    A.findOneAndUpdate()                             // returns Query
    

    在官方API页面中没有表达的另一个实现是我更喜欢使用的 Promise 基本实现,它允许你有 .catch ,你可以在那里处理你所有的各种错误 .

    let cat: catInterface = {
            name: "Naomi"
        };
    
        Cat.findOneAndUpdate({age:17}, cat,{new: true}).then((data) =>{
            if(data === null){
                throw new Error('Cat Not Found');
            }
            res.json({ message: 'Cat updated!' })
            console.log("New cat data", data);
        }).catch( (error) => {
            /*
                Deal with all your errors here with your preferred error handle middleware / method
             */
            res.status(500).json({ message: 'Some Error!' })
            console.log(error);
        });
    
  • 30

    这是 findOneAndUpdate 的更新代码 . 有用 .

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

    对于那些使用本机承诺的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 */ }
    
  • 341

    默认情况下findOneAndUpdate返回原始文档 . 如果您希望它返回修改后的文档,则将选项对象 { new: true } 传递给函数:

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

相关问题