Creating Multifield Indexes in Mongoose / MongoDB
MongodbMongooseMongodb Problem Overview
I'm trying to find documentation, to no avail, on how to create multi-field indexes in Mongoosejs. In particular I have two fields that need to be indexed and unique. What is an example mongoose schema that indexes two fields together?
Mongodb Solutions
Solution 1 - Mongodb
You call the index
method on your Schema
object to do that as shown here. For your case it would be something like:
mySchema.index({field1: 1, field2: 1}, {unique: true});
Solution 2 - Mongodb
Defining indexes at the schema level is necessary when creating compound indexes.
animalSchema.index({ name: 1, type: -1 });
Solution 3 - Mongodb
Following command can be used to create compound index for nested json:
db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1})
Mongo json structure is like :
{"_id":"648738"
"account": {
"id": "123",
"customerId": 7879,
"name": "test"
..
..
}
}
I have tested with sample data it is perfectly working as expected.
Solution 4 - Mongodb
By the way, the accepted answer is wrong, as per https://stackoverflow.com/a/52553550/129300 you should wrap the field names in single quotes, ie:
mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
Happy Day!