【问题标题】:Mongoose: Get doc _id after upsertMongoose:在 upsert 后获取 doc _id
【发布时间】:2012-10-24 07:40:22
【问题描述】:

有没有办法在 upsert 之后获取记录_id?

我看过这篇文章 (How to insert a doc into mongodb using mongoose and get the generated id?),但这只是针对插入,而不是更新。

此外,使用 MongoDB,您可以使用 getlasterror (https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/ehZ11QY-OUw) 获取 _id,但 Mongoose 不提供对它的访问 (https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/pSv6WrasvWg)

谢谢

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    在选项对象中使用 Mongoose 的 findOneAndUpdate 方法和 upsert: true

    var query = { name: 'borne' },
        data = { name: 'jason borne' },
        options = { upsert: true };
    Model.findOneAndUpdate(query, data, options, function (err, object) {
        /* use object._id */
    });
    

    【讨论】:

    • 请注意,如果您希望返回 更新的 文档,并且在它不存在并且被插入 new 文档的情况下,您将想在选项中添加 new: true : options = { upsert: true, new: true };
    【解决方案2】:

    promise 的另一种可能性:

    Model.findOneAndUpdate(query, data, options, function (err, object) {
    })).then((result) => {
        /* return result.upserted[0]._id */
    })
    

    ...result 如下:

    { n: 1,
      nModified: 0,
      upserted: [ { index: 0, _id: /* some id */ } ],
      ok: 1 }
    

    【讨论】:

      【解决方案3】:

      如果您希望返回更新的文档,并且在它不存在并且被插入新文档的情况下。以下是您需要设置的选项。

      对选项设置新:true:options = { upsert: true, new: true };

      来源:根据 Jamiel 的评论,我将他的评论添加为答案,因为当不存在文档并由 upsert 创建时,我很难找到该 _id(我正在尝试创建自己的扩展方法) .

      【讨论】:

        猜你喜欢
        • 2014-10-08
        • 2018-03-11
        • 2011-05-24
        • 2012-01-19
        • 1970-01-01
        • 2013-06-19
        • 1970-01-01
        • 2021-02-15
        • 2012-06-09
        相关资源
        最近更新 更多