Indexes in models.

suggest change

MongoDB supports secondary indexes. In Mongoose, we define these indexes within our schema. Defining indexes at schema level is necessary when we need to create compound indexes.

Mongoose Connection

var strConnection = 'mongodb://localhost:27017/dbName';
var db = mongoose.createConnection(strConnection)

Creating a basic schema

var Schema = require('mongoose').Schema;
var usersSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    created: {
        type: Date,
        default: Date.now
    }
});

var usersModel = db.model('users', usersSchema);
module.exports = usersModel;

By default, mongoose adds two new fields into our model, even when those are not defined in the model. Those fields are:

_id

Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB’s default behavior. If you don’t want an _id added to your schema at all, you may disable it using this option.

var usersSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    }, {
        _id: false 
});

**__v or versionKey**

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable.

You can easy disable this field in the model configuration:

var usersSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    }, {
    versionKey: false 
});

Compound indexes

We can create another indexes besides those Mongoose creates.

usersSchema.index({username: 1 });
usersSchema.index({email: 1 });

In these case our model have two more indexes, one for the field username and another for email field. But we can create compound indexes.

usersSchema.index({username: 1, email: 1 });

Index performance impact

By default, mongoose always call the ensureIndex for each index sequentially and emit an ‘index’ event on the model when all the ensureIndex calls succeeded or when there was an error.

In MongoDB ensureIndex is deprecated since 3.0.0 version, now is an alias for createIndex.

Is recommended disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option config.autoIndex to false.

usersSchema.set('autoIndex', false);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents