findAndModify - MongoError: exception: must specify remove or update

巧了我就是萌 提交于 2019-12-10 02:30:27

问题


Id like to update an array and return the doc. Is my findAndModify syntax correct?

this.becomeFollower = function(title, username, callback){
    "use strict"

    posts.findAndModify({
        query: {"title":title, "roster":"yes"},
        update: { "$addToSet": { "followers":username } },
        new: true,
        upsert: true
        }, 
        function(err, doc){
            console.log('find and modified  ' +doc);
        });

}

I had no problem using this:

    posts.update({"title":title, "roster":"yes"}, { "$addToSet": { "followers":username } }, function(err, roster){
        "use strict"
        if(err) return callback(err, null);
        callback(err, roster);
    });

回答1:


Check out the docs for node-mongodb findAndModify; the signature looks like:

collection.findAndModify(query, sort, update, options, callback)

So you should do:

  posts.findAndModify(
    {"title":title, "roster":"yes"},
    [['_id','asc']],
    { "$addToSet": { "followers":username } },
    {new: true, upsert: true}, 
    function(err, doc){
        console.log('find and modified  ' +doc);
    }
  );

The sort argument is probably optional, but it's unclear so I included it in the example.



来源:https://stackoverflow.com/questions/22671946/findandmodify-mongoerror-exception-must-specify-remove-or-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!