1

All the examples I have seen for MongoDb & Mongoskin for update, have individual properties being updated, like so:

    // this works when I specify the properties
    db.collection('User').update({_id: mongoskin.helper.toObjectID(user._id)}, 
     {'$set':{displayName:user.displayName}}, function(err, result) {
        if (err) throw err;
        if (result){ res.send(result)}
    });

But what if I wanted the whole object/document to be updated instead:

// this does not appear to work 
 db.collection('User').update({_id: mongoskin.helper.toObjectID(user._id)}, {'$set':user},
    function(err, result){
    // do something
 }

It returns the error:

// It appears Mongo does not like the _id as part of the update

    MongoError: After applying the update to the document {_id: ObjectId('.....

To overcome this issue, this is what I had to do to make things work:

  function (req, res) {
    var userId = req.body.user._id
    var user = req.body.user;
    delete user._id;

    db.collection('User').update({_id: mongoskin.helper.toObjectID(userId)}, 
       {'$set':user}, function(err, result) {   
        if (err) throw err;
        console.log('result: ' + result)
        if (result){ res.send(result)}
    });
})

It there a more elegant way of updating the whole document, instead of hacking it with:

   delete user._id

1 Answers1

0

If you want to update the whole object, you do not need a $set. I am not aware of mongoskin, but in shell you would do something like:

var userObj = {
   _id: <something>
   ...
};
db.user.update({_id: user._id}, user);

Which I think can be translated in your mongoskin in the following way.

db.collection('User').update({_id: user._id}, user, function(){...})

But here is the problem. You can not update _id of the element in Mongo. And this is what your error tells you. So you can remove the _id from your user object and have it separately. Search by this separate _id and update with a user object without _id.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • Isn't that exactly what my hack job is doing? –  Apr 01 '15 at 21:40
  • @user1177440 sorry, somehow missed it. As for your question regarding a better way: no there is no way you can update _id of the object. So you should get rid of it before the update. A more elegant is not to have it there in the first place. – Salvador Dali Apr 01 '15 at 21:49