在Mongo NodeJS中使用bulkinsert处理错误

我正在使用NodeJS与MongoDB和Express。 我需要将logging插入到必填电子邮件字段的集合中。 我正在使用insertMany函数来插入logging。 当插入唯一的电子邮件时它工作正常,但是当input重复的电子邮件时,操作突然中断。

我尝试使用try catch打印错误消息,但一旦插入重复的电子邮件,执行就会失败。 我想执行继续并存储重复项。 我想得到插入/失败logging的最终列表。

错误信息:

Unhandled rejection MongoError: E11000 duplicate key error collection: testingdb.gamers index: email_1 dup key: 

有什么办法来处理错误,或者除了insertMany之外还有其他的方法吗?

更新:

电子邮件是我collections中的一个独特领域。

如果要继续插入所有非唯一文档而不是停止第一个错误,请考虑将{ordered:false}选项设置为insertMany() ,例如

db.collection.insertMany([,,…],{ordered:false})

根据文档 ,无序操作将继续处理队列中剩余的任何写操作,但仍会在BulkWriteError中显示错误。

我不能发表评论,所以答案是:你是使用此字段的唯一索引数据库集合,或者您的模式具有该字段的唯一属性? 请分享有关您的代码的更多信息。

来自MongoDb文档:

“为任何属于唯一索引(例如_id)的键插入重复值会引发exception。以下尝试插入具有已存在的_id值的文档:”

 try { db.products.insertMany( [ { _id: 13, item: "envelopes", qty: 60 }, { _id: 13, item: "stamps", qty: 110 }, { _id: 14, item: "packing tape", qty: 38 } ] ); } catch (e) { print (e); } 

由于_id:13已经存在,下面的exception被抛出:

 BulkWriteError({ "writeErrors" : [ { "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: restaurant.test index: _id_ dup key: { : 13.0 }", "op" : { "_id" : 13, "item" : "envelopes", "qty" : 60 } } ], (some code omitted) 

希望能帮助到你。

由于您知道由于重复的键插入而发生错误,因此可以将初始对象数组分成两部分。 一个具有唯一的密钥,另一个具有重复。 通过这种方式,您可以操作一份重复项目列表以及要插入的原稿列表。

 let a = [ {'email': 'dude@gmail.com', 'dude': 4}, {'email': 'dude@yahoo.com', 'dude': 2}, {'email': 'dude@hotmail.com', 'dude': 2}, {'email': 'dude@gmail.com', 'dude': 1} ]; let i = a.reduce((i, j) => { i.original.map(o => o.email).indexOf(j.email) == -1? i.original.push(j): i.duplicates.push(j); return i; }, {'original': [], 'duplicates': []}); console.log(i);