Nick S. Nick S. - 1 month ago 5x
Node.js Question

How should mongoose's model.on('index', ...) be used?

In looking at the documentation for

, it appears that indexing may be specified on an object like so:

var MyModelSchema = new Schema({ name: String, index: true });
var MyModel = mongoose.model('MyModel', MyModelSchema);
MyModel.on('index', function()

Per the documentation, Mongoose will call
upon startup unless the
option is explicitly set to false on the schema. Once this is completed, the
event will be emitted on the model, which would trigger the callback.

My understanding is that this allows a user of a model to ensure that all indexing has been completed prior to use of a model.

I believe I heard mention of doing this via
, although I'm not sure how this could be done. Maybe there is another way to guarantee completion of this indexing operation prior to other parts of the application relying on the exported model?

How should this properly be used?


The 'index' event on your model is there to alert you to any errors that occurred in the model's ensureIndex calls. You don't need to delay use of the model until the event fires. That would get pretty messy.