我正在node.js环境中学习mongodb,当我使用insertOne()函数添加相同的对象时,我在指南针中看到它正在生成具有不同_id的新对象。在这种情况下防止重复的最佳做法是什么?
在您的架构中,您可以将该字段指定为唯一。 例如,对于用户集合,我们考虑
name
、userId
和 city
等字段。在此,userId
字段需要是唯一的,然后我们可以添加模式,如下所示:
const UserSchema = new mongoose.Schema({
name: string,
userId: {
type: number,
required: true
index: { unique: true },
},
city: String,
})
因此,在插入记录时,它将获得 validated 并在记录中
userId
的重复值的情况下抛出错误。