Mongodb how to enforce a unique db reference 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,
},
How can I make sure that all userWhoLiked
fields are unique?
You should build a unique index, then in the case of an insert/update of a document with a duplicate userWhoLiked
value you'll get duplicate key error thrown.