Mongodb 如何强制执行唯一的数据库引用 id?
const LikeSchema = new mongoose.Schema({
idOfPost: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post',
required: true,
},
userWhoLiked: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
unique: true // This is not working? Why?
},
date=:{
default: Date.now,
required: true,
type: Date,
},
如何确保所有 userWhoLiked
字段都是唯一的?
最佳答案
您应该构建一个 unique index ,那么在插入/更新具有重复 userWhoLiked
值的文档时,您将抛出重复键错误。
关于Mongodb如何强制执行唯一的数据库引用ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60640628/