[英]MongoDb/Mongoskin - CLEANLY Update entire document w/o specifying properties
我在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)}
});
但是如果我想更新整个对象/文档怎么办:
// this does not appear to work
db.collection('User').update({_id: mongoskin.helper.toObjectID(user._id)}, {'$set':user},
function(err, result){
// do something
}
它返回错误:
// It appears Mongo does not like the _id as part of the update
MongoError: After applying the update to the document {_id: ObjectId('.....
为了克服这个问题,这就是我要做的事情:
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)}
});
})
它提供了一种更优雅的方式来更新整个文档,而不是使用以下方法来对其进行破解:
delete user._id
如果要更新整个对象,则不需要$ set。 我不知道mongoskin,但是在shell中,您将执行以下操作:
var userObj = {
_id: <something>
...
};
db.user.update({_id: user._id}, user);
我认为可以通过以下方式在您的蒙古皮中进行翻译。
db.collection('User').update({_id: user._id}, user, function(){...})
但这是问题所在。 您无法在Mongo中更新元素的_id 。 这就是您的错误告诉您的内容。 因此,您可以从user
对象中删除_id
并单独使用。 通过此单独的_id
搜索,并使用不带_id
的user
对象进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.