Skip to content
Advertisement

How to make sure that objects do not have the same two element in mongoose schema?

I am making the following mongoose schema and i want to make sure that no object has the same autherFirstName and autherLastName. object may have one in common but not both of them

const authorShcema = new mongoose.Schema({
    autherFirstName: {type: String, minLength: 2, required: true},
    autherLastName: {type: String, minLength: 2, required: true},
    autjorDob: {type: Date, required: true},
    authorImage: {type: String},
    authorBooks: [{type: mongoose.Schema.Types.ObjectId, ref: "Book"}],     
});

Advertisement

Answer

https://mongoosejs.com/docs/2.7.x/docs/indexes.html

Create a composite unique index

authorShcema.index({ autherFirstName: 1, autherLastName: 1 }, { unique: true });
Advertisement