Indexes in models.
suggest changeMongoDB 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 mongoose = require('mongoose');
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 Mongoose first creates it. This key's value is the document's internal revision. The property name is configurable.
You can disable the field in the schema options:
var usersSchema = new Schema({
username: {
type: String,
required: true,
unique: true
}
}, {
versionKey: false
});
Compound indexes
You can create more indexes besides the ones Mongoose creates. unique: true already creates an index.
usersSchema.index({username: 1 });
usersSchema.index({email: 1 });
In this case the model has two more indexes, one on username and one on email. A compound index covers both fields:
usersSchema.index({username: 1, email: 1 });
Index performance impact
By default, Mongoose calls createIndexes for each index when it connects and emits an index event on the model when that finishes or fails. ensureIndex is a deprecated alias of createIndex.
Building indexes at startup can block a busy database. Turn that off with the schema autoIndex option, or set autoIndex: false on the connection.
usersSchema.set('autoIndex', false);