FindAndModify - MongoError: exception: delete or update must be specified

I like updating the array and returning the document. Is 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 problems with this:

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

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

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 argument sortis probably optional, but it is unclear, so I included it in the example.

+9
source

Source: https://habr.com/ru/post/1533608/


All Articles