简体   繁体   中英

MongoDb/Mongoskin - CLEANLY Update entire document w/o specifying properties

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM