使用Mongo NodeJS中的bulkinsert处理错误

Ani*_*udh 9 mongodb node.js

我正在使用NodeJS和MongoDB和Express.我需要将记录插入到必须包含电子邮件字段的集合中.我正在使用insertMany函数来插入记录.插入唯一的电子邮件时,它可以正常工作,但是当输入重复的电子邮件时,操作会突然中断.

我尝试使用try catch打印错误消息,但插入重复的电子邮件后执行失败.我希望执行继续并存储重复项.我想获得插入/失败的记录的最终列表.

错误信息:

Unhandled rejection MongoError: E11000 duplicate key error collection: testingdb.gamers index: email_1 dup key: 
Run Code Online (Sandbox Code Playgroud)

有没有办法处理错误或除了insertMany还有其他方法吗?

更新:

电子邮件是我收藏中的一个独特字段.

Nic*_*ell 6

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

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

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


dpe*_*ini 0

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

\n\n

来自 MongoDb 文档:

\n\n

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

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

由于 _id: 13 已经存在,因此抛出以下异常:

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

希望能帮助到你。

\n