[英]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: 我在MongoDb和Mongoskin上看到的所有用于更新的示例都具有要更新的各个属性,例如:
// 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. 如果要更新整个对象,则不需要$ set。 I am not aware of mongoskin, but in shell you would do something like:
我不知道mongoskin,但是在shell中,您将执行以下操作:
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 .
您无法在Mongo中更新元素的_id 。 And this is what your error tells you.
这就是您的错误告诉您的内容。 So you can remove the
_id
from your user
object and have it separately. 因此,您可以从
user
对象中删除_id
并单独使用。 Search by this separate _id
and update with a user
object without _id
. 通过此单独的
_id
搜索,并使用不带_id
的user
对象进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.