【发布时间】:2015-04-02 05:39:09
【问题描述】:
我看到的所有用于更新 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
【问题讨论】: