Creating Multifield Indexes in Mongoose / MongoDB

Dan picture Dan · Sep 25, 2012 · Viewed 70.9k times · Source

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?

Answer

JohnnyHK picture JohnnyHK · Sep 25, 2012

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});