15

I'm 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,oneand two, and strict:false because there can be other fields with undetermined names.

I would like the combination of one and two to be unique. That means there could be multiple documents with the same one or the same two, but none of them should have the same one and two combination.

Can this be achieved with Mongoose?

Juicy
  • 11,840
  • 35
  • 123
  • 212

1 Answers1

33

You can enforce a unique constraint on compound indexes, and you can do this in Mongoose using the index() method of the schema, 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 );
chridam
  • 100,957
  • 23
  • 236
  • 235