【问题标题】:Return Inserted Document in MongoDb ( Node.js )在 MongoDb ( Node.js ) 中返回插入的文档
【发布时间】:2021-10-03 21:35:33
【问题描述】:

我需要向 MongoDB 中插入一个文档并返回新插入的文档。我使用了 db.collection('collection__name').insertOne('要插入的数据').then((res)=>{ res.send(res.ops[0]) })

错误:未定义操作。

insertOne 只返回插入的文档的 _id,而不是整个文档☹ 但之前它用于返回整个文档。我使用的是 mongoclient 而不是 mongoose,在 mongoose 中它会返回整个文档,但我不喜欢使用 mongoose。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    他们从 mongo 4.0 开始删除了 ops 字段,您可以在此处找到架构: https://mongodb.github.io/node-mongodb-native/4.0/interfaces/insertoneresult.html#insertedid

    我刚刚查看了mongoose的源代码,他们实际上是根据insertId字段调用findOne:

        const promise = collection.insertOne({ foo: 'bar' }, {})
          .then(result =>
            collection.findOne({ _id: result.insertedId })
          ).then(doc => {
            assert.strictEqual(doc.foo, 'bar');
          });
    

    (https://github.com/Automattic/mongoose/blob/80245edf5aeab304411681035f7f4153dbd2b692/test/collection.test.js#L50).

    似乎唯一的解决方案是使用旧的库版本(没有打字稿)或使用返回的 id 字段调用 findOne。我刚刚遇到了同样的问题并添加了额外的 findOne 调用,因为我不想放弃 typescript。

    【讨论】:

    • 嘿@anand-ca,这能回答你的问题吗?如果是,请标记我的答案:)
    猜你喜欢
    • 2017-04-07
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2022-10-06
    • 1970-01-01
    • 2016-05-02
    • 2014-11-16
    相关资源
    最近更新 更多