mongodb中是否有一种方法可以使insertOne无法创建重复的索引文档而不会引发错误?

问题描述 投票:0回答:1

我想避免创建重复的文档,因此在搜索方法时,我发现的第一个解决方案是this answer

db.collection.update(doc, doc, {upsert:true})

但是与insertOne相比,这确实很慢,所以我查看了second answer

db.collection.createIndex( { propertyName: 1 }, {unique:true} )

这似乎是一种性能更好的解决方案,但问题不只是不插入重复项,而是引发错误:

(node:97200) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: main.dir index: path_1 dup key: { propertyName: "propertyName123" }

是否有设置使其不会抛出错误,或者我需要在此处使用try catch吗?

node.js mongodb
1个回答
0
投票

您是否尝试过{ upsert: true }?这可能是您要寻找的。

db.collection.createIndex( { propertyName: 1 }, {upsert: true} )

Upsert就像更新+插入,类似于PUT操作

© www.soinside.com 2019 - 2024. All rights reserved.