【问题标题】:MongoDB findAndModify() adds query to update clauseMongoDB findAndModify() 将查询添加到更新子句
【发布时间】:2012-04-30 15:20:04
【问题描述】:

我正在 Node 中创建一个包含一些 CRUD 组件的应用程序。在我的一个数据对象上,我有一个 save() 方法,如果对象具有在集合中找到的 id,则更新记录,如果没有,则更新插入新文档。此外,如果进行 upsert,我想取回 Mongo 生成的文档的 _id。

似乎findAndModify 会这样做,而且确实会从数据库返回一个_id 值。在我的查询子句中,我按 _id 过滤。如果我的数据对象没有 id,Mongo 会正确执行 upsert,但是,无论它返回什么 _id 值,除了我在 update 子句中设置的键之外,它还会在根据我在query 子句中使用的值创建文档。为了清楚起见,一些代码:

User.prototype.save = function(callback) {
    var that = this;

    var args = {
        'query'     : { _id: this.getId() }, //getId() returns empty string if not set
        'update'    : { $set : {
            firstName   : this.firstName,
            lastName    : this.lastName,
            email       : this.email
          //_id        : this.getId()
          // which is blank, is magically getting added due to query clause
        }},
        'new'       : true,
        'upsert'    : true,
        'fields'    : {'_id' : true}
    };

    this.db.collection(dbName).findAndModify(args, function(err, doc){
        if(!that.getId()) {
            that.setId(doc._id);
        }

        if (typeof(callback) === "function"){
            callback.call(that);
        }
    }); 
}

我只是在寻找更新的语义,它也恰好在 upsert 上返回 Mongo 生成的 _id。我不希望额外附加 query 子句的值,就好像它们在 update 映射中一样。有什么方法可以实现我的目标吗?

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    您可以使用新的new require('mongodb').ObjectID() 生成_id 客户端 然后你可以做一个常规的 upsert(不需要 findandmodify),因为你已经有了 _id。

    但是,如果您使用 findAndModify,请记住节点驱动程序在位置上接受此函数的参数,而不是作为对象(如在常规 mongo shell 中)。 使用节点驱动程序进行查找和修改的正确格式如下所示:

    collection.findAndModify(criteria, sort, update[, options, callback])

    (选项和回调是可选参数)。完整文档在这里: https://github.com/mongodb/node-mongodb-native/blob/master/docs/insert.md

    【讨论】:

    • 我实际上使用的是 MongoJS,它是本地 Mongo 驱动程序的包装器,它似乎接受对象语法。但是您关于生成 id 客户端的观点似乎是最好的解决方案。不过,我仍然想知道为什么查询子句中的条件在 upsert 期间都被评估并添加到记录中。
    • @DuxPrime 这是设计使然 - 如果您提供非空查询,“更新插入”意味着如果没有文档匹配该查询,它必须创建一个 - 因此它被添加到正在创建的记录中.
    • 以下应该可以工作... _id: this.getId() ||新的 mongodb.ObjectID()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多