mongodb - 使用 update() 获取受影响文档的 ID

标签 mongodb meteor mongodb-query

我用它来做一个 upsert:

Articles.update(
    { title: title },
    { 
        title: title,
        parent: type
    },
    { upsert: true }, 
    function(res) {
        return console.log(res);
    }
);

console.log(needToGetID);

现在我需要获取已更新或插入的文档的 _id。我以为我可以通过回调得到它,但是 res 是未定义的。 我假设只有一个由查询定义的唯一文档。

更新

忘了说我用的是 meteor ……

最佳答案

.update() 的意图基本上只是“更新”匹配的文档(因为“多”也可以在这里应用)并完成它,因此特别考虑到这个“可以”应用于多个文档然后返回这些信息不会真的就该操作而言是有意义的。

但是,如果您的意图是修改单个“特定文档”,那么 .findOneAndUpdate()假设您使用的是 Mongoose ,该方法将适用:

Articles.findOneAndUpdate(
    { title: title },
    {
        title: title,
        parent: type
    },
    { upsert: true, new: true  }, 
    function(res) {
        return console.log(res);
    }
);

还要注意 new: true 这很重要,因为没有它,默认行为是返回文档“在”被语句修改之前。

无论如何,由于这里的返回是匹配和修改的文档,所以 _id 和任何其他值都会出现在响应中。


使用 meteor ,您可以添加 plugin启用 .findAndModify() 这是根方法:

meteor add fongandrew:find-and-modify

然后在代码中:

Articles.findAndModify(
    {
        "query": { title: title },
        "update": {
            title: title,
            parent: type
        },
        "upsert": true, 
        "new": true  
    }, 
    function(res) {
        return console.log(res);
    }
);

请注意,您还应该真正使用 $set运算符,因为没有它,更改基本上会“覆盖”目标文档:

Articles.findAndModify(
    {
        "query": { "title": title },
        "update": {
            "$set": {
                "parent": type
            }
        },
        "upsert": true, 
        "new": true  
    }, 
    function(res) {
        return console.log(res);
    }
);

关于mongodb - 使用 update() 获取受影响文档的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679561/

相关文章:

javascript - 铁 :Router add events on change router

没有 'www' 前缀, meteor 链接不起作用

mongodb - 没有 $unwind 的 $group 内部数组值

MongoDB $redact 过滤掉数组的一些元素

mongodb - 所以......这个NoSQL的东西

json - 如何根据 Mongoose 中的子文档值检索父文档?

node.js - 在 React 中呈现的 Blaze LoginButtons 模板 - 登录仅适用于主页

javascript - 如何在 Node 中创建一个带有变量名的 Mongo 集合?

javascript - 如何执行 Mongoose 验证功能仅用于创建用户页面而不编辑用户页面?

mongodb - 将 ISO 日期转换为 yyyy-mm-dd 格式