When should I call ensureIndex
? Before inserting a single record, after inserting a single record, or before calling find()
?
It seems my comment has been a little misunderstood, so I'll clarify. It doesn't really matter when you call it so long as it's called at some point before you call find() for the first time. In other words, it doesn't really matter when you create the index, as long as it's there before you expect to use it.
A common pattern that I've seen a lot is coding the ensureIndex
at the same time (and in the same place) as the find()
call. ensureIndex
will check if the index exists and create it if it doesn't. There is undoubted some overhead (albeit very small) in calling ensureindex before ever call to find() so it's preferable not to do this.
I do call ensureIndex
in code to simplify deployments and to avoid having to manage the db and codebase separately. The tradeoff of ease of deployment balances out the redundancy of subsequent calls to ensureIndex (for me.)
I'd recommend calling ensureIndex once, when your application starts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With