我正在使用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还有其他方法吗?
更新:
电子邮件是我收藏中的一个独特字段.
我可以\xc2\xb4t 发表评论,所以答案是:\你的数据库集合是否使用该字段的唯一索引,或者你的模式具有该字段的唯一属性?请分享有关您的代码的更多信息。
\n\n来自 MongoDb 文档:
\n\n“为属于唯一索引的任何键(例如 _id)插入重复值会引发异常。以下尝试插入具有已存在的 _id 值的文档:”
\n\ntry {\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}\nRun Code Online (Sandbox Code Playgroud)\n\n由于 _id: 13 已经存在,因此抛出以下异常:
\n\nBulkWriteError({\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)\nRun Code Online (Sandbox Code Playgroud)\n\n希望能帮助到你。
\n| 归档时间: |
|
| 查看次数: |
997 次 |
| 最近记录: |