11

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);
    });
Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#upsert-and-unique-index `When findAndModify() includes the upsert: true option and the query field(s) is not uniquely indexed, the method could insert a document multiple times in certain circumstances.` I guess that's why `sort` is needed. – SCaffrey Mar 22 '18 at 15:37
  • 1
    well, https://stackoverflow.com/a/24648693/4597306 helps finally. Also https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html – SCaffrey Mar 22 '18 at 16:34
  • Attention please: the [.findAndModify()](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#findAndModify) method in the node native driver implementation is different from the mongo shell implementation. See also here https://stackoverflow.com/a/24326067/1335142 – Serhii Popov Feb 19 '22 at 14:13

1 Answers1

19

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.

sgress454
  • 24,870
  • 4
  • 74
  • 92
  • YOUR THE MAN! THANK U! I thought that was a little unclear here http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/ – Squirrl Mar 27 '14 at 03:58
  • Why is sort not surrounded by {}? – Squirrl Mar 27 '14 at 04:17
  • 2
    Sort is an array, where each element is itself an array with the first element is a key to sort on, and the second element is the sort direction. Arrays are surrounded by square brackets. – sgress454 Mar 27 '14 at 04:25