【问题标题】:MongoDb/Mongoskin - CLEANLY Update entire document w/o specifying propertiesMongoDb/Mongoskin - 在不指定属性的情况下干净地更新整个文档
【发布时间】: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

【问题讨论】:

    标签: mongodb mongoskin


    【解决方案1】:

    如果要更新整个对象,则不需要 $set。我不知道 mongoskin,但在 shell 中你会做类似的事情:

    var userObj = {
       _id: <something>
       ...
    };
    db.user.update({_id: user._id}, user);
    

    我认为可以通过以下方式在您的 mongoskin 中翻译。

    db.collection('User').update({_id: user._id}, user, function(){...})
    

    但这就是问题所在。 您不能在 Mongo 中更新元素的 _id。这就是你的错误告诉你的。因此,您可以从 user 对象中删除 _id 并单独拥有它。通过这个单独的_id 搜索并使用不带_iduser 对象进行更新。

    【讨论】:

    • 这不正是我的黑客工作正在做的事情吗?
    • @user1177440 抱歉,不知怎的错过了。至于您关于更好方法的问题:不,您无法更新对象的 _id 。所以你应该在更新之前摆脱它。更优雅的是一开始就没有它。
    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多