Octtavius Octtavius - 2 months ago 19
Node.js Question

Can I add index dynamically to my schema in Mongoose?

For example I have the following structure of documents:

"subject":"Joe owns a dog",
"content":"Dogs are man's best friend",
"likes": 60,

And the schema would be:

var schema = new Schema({
subject: {type: String},
content: {type: String},
likes: {type: int},
year: {type: int},
language: {type: String}

schema.createIndex({"subject": "text"});

Can I dynamically remove the index and create another one with more fields?

So if now it searches for a keyword in subject field, I would like to change it dynamically and search in "subject" and "content". to change to:

schema.createIndex({"subject": "text", "content": "text"});

Do you think that is possible?

Thanks a lot.


The answer is yes, you can build dynamically indexes.

Using ensureIndex(...); mongoDB function.

To remove the index use dropIndexes(...); mongoDB function.

But I'm warning you, manipulating indexes is a major action, that's gonna have major impact on performances depending the size of your collection.

By default mongoDB create index using foreground method, take a look at what mongoDB says about it:

By default, creating an index blocks all other operations on a database. When building an index on a collection, the database that holds the collection is unavailable for read or write operations until the index build completes

So if you want really create indexes dynamically, maybe you should consider to make mongoDB to create index in background:

For potentially long running index building operations, consider the background operation so that the MongoDB database remains available during the index building operation.

Here is full mongoDB docuemntation about Indexes

ensureIndex(...) documentation

dropIndexes(...) documentation

getIndexes(...) documentation

How to call directly mongoDB methods from mongoose