【问题标题】:Does MongoDB InsertMany returns both the successfully inserted and failed documents?MongoDB InsertMany 是否返回成功插入和失败的文档?
【发布时间】:2019-11-24 17:25:40
【问题描述】:

我们正在使用 MongoDB insertMany(),我想同时获取成功插入的文档和失败的文档。

有些文档无法插入,因为我们首先放置了唯一的文档(按电话号码),然后如果代码遇到相同的电话号码,则会将字符串 DUP 添加到电话号码。

代码:

try {
       await Leads.insertMany(leadsToInsert, {
        ordered: false
      });

}

catch(err) {

 if (err.code === 11000) {
        // Here we get the errors 
        const ordersIDsWithDuplicates = err.result.result.writeErrors;
 }

}

在 catch 块中,我们获取失败的文档。

有没有办法在不查询数据库的情况下获取我们成功插入的文档?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    当然,它在insertedIds 下与writeErrors 处于同一级别:

    {
      "name":"BulkWriteError",
      "driver":true,
      "code":11000,
      "writeErrors":[ ... ],
      "writeConcernErrors":[ ... ],
      "insertedIds":[{"index":0,"_id":7085598},{"index":1,"_id":7085599} ... ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2021-07-13
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多