Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make combination of two fields unique in my collection [duplicate]

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?

like image 912
Juicy Avatar asked Jan 12 '16 11:01

Juicy


People also ask

How do you make a unique field combination in Salesforce?

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.

How to make fields unique in MongoDB?

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

How do you make two fields unique in Django?

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.


1 Answers

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 );
like image 142
chridam Avatar answered Sep 17 '22 12:09

chridam