5
votes

I am making an android app and I am using nodeJS with mongoDB on the server side, now actually till now I was coding all in development, but now I want my app to be in production, now as I read the docs on mongoose they have written that :

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. While nice for development, it is recommended this behaviour be disabled in production since index creation can cause a significant performance impact. Disable the behaviour by setting the autoIndex option of your schema to false

Now can anyone please tell me what is this, I mean, I have some fields that I have indexed now why disable autoIndex, I am not indexing every field just some of them I have also seen this question before on StackOverflow, but no one explained this in detail, I have read the answers here

Mongoose indexing in production code
Mongoose call ensureIndex on startup, but it's not recommended. So why it's default?

Also one more question I was just wondering that as all my indexes are on my mongoDB part so what are the use of describing them even in schema level, I mean think this way every operation CRUD every thing happens on database and on database level we have defined all the indexes so why should we again index them at schema level please answer I am very new on this thats why didn't know much bout this I know I am missing some big part of the puzzle but it would be really helpful if someone can share some light on this.

1

1 Answers

0
votes

Question 1: Why should I disable autoMigrate on production?

For many projects, production databases are very large compared to dev databases, so if you would migrate the database (adding new indexes etc) on application startup, you'd experience a lot of unexpected downtime.

It's best practice to do heavy production migrations outside of the application life cycle, either by using a migration framework or by manually creating indexes on your production instance directly.

Question 2: Why do I need to create indexes in mongoose?

You don't strictly need them - you could just leave them out of your schema definition and always create your indexes directly in mongodb.

But they give you some convenience: In dev environments where auto-migration is enabled, defining the index on your schema allows mongoose to create the indexes in your dev mongodb on your behalf.

And if you use migrate-mongoose as above, you can also use them for production migrations. That reduces repetition and room for human error.