当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: