gpt4 book ai didi

javascript - mongodb continueOnError 不抑制重复键错误

转载 作者:行者123 更新时间:2023-12-02 14:10:36 24 4
gpt4 key购买 nike

我正在尝试保留一个具有唯一键的集合。要插入的数据来自各个分布式位置(尽管各个文档是不可变的),并且可能包含重复项。我希望简单地插入记录并使用 continueOnError 抑制重复键错误,但仍然抛出重复键错误。代码看起来像这样...

fetchStatuses(statusId)
.then(results => connection
.then(db => db.collection('statuses').ensureIndex({id: 1}, {
unique: true, dropDups: true
})
.then(() => db.collection('statuses').insert(results, {continueOnError: true, safe: true}))
.then(response => {
winston.info(`Inserted ${response.insertedCount} statuses into mongo`);
return results;
})

最佳答案

您可能想尝试像 docs 中所述的无序插入。 :

The following example performs an unordered insert of three documents. With unordered inserts, if an error occurs during an insert of one of the documents, MongoDB continues to insert the remaining documents in the array.

db.products.insert(
[
{ _id: 20, item: "lamp", qty: 50, type: "desk" },
{ _id: 21, item: "lamp", qty: 20, type: "floor" },
{ _id: 22, item: "bulk", qty: 100 }
],
{ ordered: false }
)

据我了解文档,在这种情况下不会抛出错误,而是设置了结果对象的特殊属性

If the insert() method encounters a non-write concern error, the results include the WriteResult.writeError field

WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.foo.$_id_ dup key: { : 1.0 }"
}
})

关于javascript - mongodb continueOnError 不抑制重复键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39635348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com