Combination of two fields unique in my collection

I am using the following Mongoose model:

var Test = db.model('Test', db.Schema({ one: { type: String, required: true }, two: { type: String, required: true } }, { strict: false }) ); 

It has two required fields: one and two and strict:false , because there may be other fields with undefined names.

I would like the combination of one and two be unique. This means that there can be several documents with the same one or the same two , but none of them should have the same combination of one and two .

Can this be done with Mongoose?

+6
source share
1 answer

You can force a unique constraint on composite indexes , and you can do this in Mongoose using the index() schema method, which defines indexes at the schema level:

 var testSchema = db.Schema({ "one": { "type": String, "required": true }, "two": { "type": String, "required": true } }, { "strict": false }); testSchema.index({ "one": 1, "two": 1}, { "unique": true }); var Test = db.model("Test", testSchema ); 
+8
source

All Articles