Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findAndModify - MongoError: exception: must specify remove or update

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);
    });
like image 221
Squirrl Avatar asked Mar 26 '14 20:03

Squirrl


1 Answers

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.

like image 96
sgress454 Avatar answered Oct 19 '22 04:10

sgress454