I have a special case where our collection needs to make sure each document is unique based on a combination of the email address, and the sweepstakes_id. I've looked all over, but I can't find how to accomplish this type of validation.
Schema definition:
var submissionSchema = new Schema({ client_id: { type: Schema.Types.ObjectId, ref: 'Client', index: true }, sweepstakes_id: { type: Schema.Types.ObjectId, ref: 'Sweepstakes', index: true }, email: { type: String, index: true }, data: { type: Schema.Types.Mixed, default: [] } });
Mongoose doesn't handle unique on its own: { name: { type: String, unique: true } } is just a shorthand for creating a MongoDB unique index on name . For example, if MongoDB doesn't already have a unique index on name , the below code will not error despite the fact that unique is true.
mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
You can enforce that using a unique index that includes both fields:
submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With