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,one
and 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?
All you have to do is create a new "Matching Rule" on your desired object (Standard or Custom), activate it, and then create a new "Duplicate Rule" and have it use the "Matching Rule" you just created/activated. Easy peasy! Save this answer.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
To make fields unique together, we create a class Meta. In this class, we specify the keyword, unique_together, and then create a tuple consisting of all the fields that we want unique together. In this case, we just want 2 fields unique together, but you can specify as many as you want, as long as it's 2 or greater.
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 );
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