120

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?

5 Answers 5

247

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});
Sign up to request clarification or add additional context in comments.

8 Comments

This is called the Compount Index in mongodb. So it creates indexes as field1 and field1 + field2. So it is first index according to field1 and then inside field1 with respect to field 2
what is the meaning of the 1 after field1: and field2: ?
@DamonYuan They set the sort order of the fields in the index. 1 is ascending, -1 would be descending.
@KetanGhumatkar It's based on the order the fields are listed in the object in the call to index.
1 and -1 specifies a ascending or a descending index key on the index field. I found docs http://mongodb.github.io/node-mongodb-native/2.1/tutorials/create-indexes/
|
13

Defining indexes at the schema level is necessary when creating compound indexes.

animalSchema.index({ name: 1, type: -1 });

Reference: http://mongoosejs.com/docs/guide.html#indexes

2 Comments

What is the meaning of 1 and -1? I couldn't find this in the documentation that you referenced to. Thanks.
I found the answer on this page: docs.mongodb.org/manual/core/indexes-introduction Thanks!
3

This should help ;)

import { Schema, Document, model } from 'mongoose';

import { IUser } from './User';
import { IMood } from './Mood';
import { ILocation } from './Location';

export interface IUserMoodLocation extends Document {
    userId?: IUser['_id'];
    moodId?: IMood['_id'];
    locationId?: ILocation['_id'];
}

const UserMoodLocationSchema: Schema = new Schema({
    userId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    moodId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Mood'
    },
    locationId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Location'
    }
});

UserMoodLocationSchema.index(
    { userId: 1, moodId: 1, locationId: 1 },
    { unique: true }
);

export const UserMoodLocation = model<IUserMoodLocation>(
    'UserMoodLocation',
    UserMoodLocationSchema
);

Comments

-4
    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.

1 Comment

We don't want that with mongooses shell we want that with node js schema
-5

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!

2 Comments

Object keys in JS can be unquoted as long as they're syntactically-valid identifiers. field1 and field2 are valid identifiers. field1.foo isn't, for example.
The answer is working though, but the accepted answer isn't wrong either as far as the object keys are valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.