首页 > 解决方案 > 防止 Mongo DB 中的重复文档

问题描述

例如,我有这个架构:

const carStatusSchema = new Schema({
carColor: { type: String, required: true },
status: { type: String, required: true },
brand: { type: String, required: true }
})

当我需要更新我的文档或创建新文档(如果它不存在)时,我会使用此代码:

const options = { upsert: true, new: true };
const filter = {
    carColor: req.body.carColor,
    brand: req.body.brand
};
const updateInfo = { status: req.body.status };

await carStatusSchema.findOneAndUpdate(filter, updateInfo, options, (err, result) => {
    if (err) { return console.log('Can\'t update data: ', err); }
    console.log('Updated data: ', result);
});

但有时,当我尝试插入新文档时,它会被重复。例如,我的收藏有这样的文档:

{_id: ObjectId(''), carColor: 'black', status: 'In Progress 03', brand: 'bmv'},
{_id: ObjectId(''), carColor: 'black', status: 'In Progress 03', brand: 'toyota'},
{_id: ObjectId(''), carColor: 'green', status: 'In Progress 01', brand: 'cherry'},

非常罕见,但是当我尝试插入类似的文档时:

{_id: ObjectId(''), carColor: 'lightGreen', status: 'In Progress 02', brand: 'cherry'}

它找不到更新的匹配项(如预期的那样)并创建两个相同的文档:

{_id: ObjectId(''), carColor: 'black', status: 'In Progress 03', brand: 'bmv'},
{_id: ObjectId(''), carColor: 'black', status: 'In Progress 03', brand: 'toyota'},
{_id: ObjectId(''), carColor: 'green', status: 'In Progress 01', brand: 'cherry'},
{_id: ObjectId(''), carColor: 'lightGreen', status: 'In Progress 02', brand: 'cherry'},
{_id: ObjectId(''), carColor: 'lightGreen', status: 'In Progress 02', brand: 'cherry'}

我知道索引,但它们不适合我,因为我可能有重复的字段值,但组合不同。如何防止这种重复?

标签: node.jsmongodbmongoose

解决方案


推荐阅读