已经阅读了很多关于此问题的信息,但似乎没有符合我的要求的内容。 有这个架构:
const TestSchema = new Schema(
{
name: {type: String, required: true},
identifier: {type: String, required: true, unique: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
}
);
我以这种方式添加新文档:
db.tests.insertMany(
[
{name: 'product 1', identifier: 'abc'}
,{name: 'product 2', identifier: 'def'}
,{name: 'product 3', identifier: 'abc'}
]
);
“标识符”字段是唯一的。我可以将其声明为“唯一”,因此不会添加重复项。但是,即使最终结果是正确的,这也会引发错误,这对我来说似乎不是一个好习惯。
使用 upsert 可能是解决方案。但是,我找不到“insertMany”的标志来直接插入。 此外,更新插入并不是我想要的。我只想跳过上面的“产品 3”,因为标识符已经存在。
所以就我而言,我不认为“独特”或“更新插入”正是我正在寻找的。还有其他解决办法吗?
答案 0 :(得分:2)
将其放在 try .. catch
语句中可以帮助您解决错误,并且只会插入 Test
文档中的第一个唯一项。
如果您想确定哪个项目有重复的 identifier
,您可以从 catch 块中的错误消息中获取。
try {
db.tests.insertMany(
[
{_id: 'abc', name: 'product 1', identifier: 'abc'}
,{_id: 'def', name: 'product 2', identifier: 'def'}
,{_id: 'abc', name: 'product 3', identifier: 'abc'}
]
);
} catch (e) {
print(e.message.match(/\d+/)[0]) // 2
}
这将插入前两个文档并打印索引 2
,在这种情况下它是重复的。
注意
我添加了 _id
,其值与 identifier
相同
如果文档未指定 _id
字段,则 mongod
添加 _id
字段并为文档分配唯一的 ObjectId。