Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique documents using multiple values in Mongoose Schema

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: []    } }); 
like image 443
Nick Parsons Avatar asked Jan 11 '13 17:01

Nick Parsons


People also ask

How do you make a Mongoose unique?

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.

What does Mongoose unique validator do?

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.

How do I set unique fields in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What does .save do Mongoose?

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.


1 Answers

You can enforce that using a unique index that includes both fields:

submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true }); 
like image 197
JohnnyHK Avatar answered Sep 29 '22 13:09

JohnnyHK