redixhumayun
redixhumayun

Reputation: 1864

How to use findAndModify with a Node.js MongoDB driver?

What is wrong with the code below?

db.get().collection('bars').findAndModify({
    barID: req.body.button
},{
    $push: {
        usersfbID: req.body.profileUser[0].facebookID,
        usersDocID: req.body.profileUser[0]._id
    }
},{
    new: true
}, function(err, doc){
    if(err){
        throw err;
    }if(doc){
        console.log('Existing document updated successfully');
        console.log(doc);
    }
});

I always get the same error,

MongoError: exception: nextSafe(): { $err: "Can't canonicalize query: BadValue bad sort specification", code: 17287 }

What am I doing wrong? Am I misusing the $push operator? Do I need to provide quotes around some of the key value pairs? This findAndModify method is driving me crazy. I have absolutely no idea what I am doing wrong.

Note: I have been through the other questions on SO regarding findAndModify, but none of those solutions is working for me. I'm sure its a small error regarding the syntax for the function.

Upvotes: 1

Views: 1943

Answers (1)

chridam
chridam

Reputation: 103475

The findAndModify method has the following signature

findAndModify(query, sort, doc, options, callback)

where

  • query <object> : The query object to locate the object to modify.
  • sort <array> : If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  • doc <object> : The fields/vals to be updated.
  • options <object> optional: Optional settings.

The reason why you are getting the error is because the sort specification is missing and instead it's reading the update doc as the sort parameter.

You need to specify the sort parameter as follows:

db.get().collection('bars').findAndModify(
    { "barID": req.body.button },   // query
    [ ["barID", 1] ],               // sort
    {
        "$push": {                   // doc
            "usersfbID": req.body.profileUser[0].facebookID,
            "usersDocID": req.body.profileUser[0]._id
        }
    },
    { "new": true },                // options
    function(err, doc){             // callback
        if (err){
            throw err;
        } else if(doc){
            console.log('Existing document updated successfully');
            console.log(doc);
        }
    }
);

Upvotes: 2

Related Questions