[英]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.