31

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: []
   }
});
Nick Parsons
  • 8,377
  • 13
  • 48
  • 70
  • Does this answer your question? [Creating Multifield Indexes in Mongoose / MongoDB](https://stackoverflow.com/questions/12573753/creating-multifield-indexes-in-mongoose-mongodb) – Shivam Dec 22 '22 at 17:12

1 Answers1

96

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

submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true });
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    What does the 1 stay for? – Matthias Max Nov 16 '15 at 14:11
  • 3
    I found the answer here: http://stackoverflow.com/questions/12573753/creating-multifield-indexes-in-mongoose-mongodb – Matthias Max Nov 16 '15 at 14:19
  • I've hear that using an index is bad for production. Does anybody know of a way that would work for production? – user1828780 Dec 16 '15 at 21:52
  • I found it at http://mongoosejs.com/docs/guide.html but maybe I am misinterpreting, "When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. Mongoose will call ensureIndex for each index sequentially, and emit an 'index' event on the model when all the ensureIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false..." – user1828780 Dec 17 '15 at 18:10
  • 1
    @user1828780 That's just a deployment concern to be aware of. See [here](http://stackoverflow.com/questions/14342708/mongoose-indexing-in-production-code). – JohnnyHK Dec 17 '15 at 18:41
  • is working fine!. just remember remove the collection if is already create – Victor Santos Jan 03 '19 at 06:24
  • Worked for me! on mongoose version 5.3.2 – Rohit Parte Oct 19 '21 at 17:18
  • 1
    @Akintunde and @Matthias Max --- The `1` indicates the sort order of the index, not whether it's true or not. `1` = `ascending`, `-1` = `descending` --- https://www.mongodb.com/docs/manual/indexes/#compound-index – Jack_Hu Apr 09 '22 at 19:13