mongoose 文檔中提到:
When your application starts up, Mongoose automatically calls
ensureIndexfor each defined index in your schema. Mongoose will callensureIndexfor each index sequentially, and emit an 'index' event on the model when all theensureIndexcalls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting theautoIndexoption of your schema tofalse, or globally on the connection by setting the optionconfig.autoIndextofalse.
在開發(fā)過程中可以使用 ensureIndex,這樣每次改動數(shù)據(jù)庫結(jié)構(gòu)時,自動生成對應(yīng)的 Index 。而在生產(chǎn)環(huán)境中,因為 ensureIndex 操作會影響性能,所以建議禁止使用。
在沒有理解 MongoDB 的生成 Index 操作前,對上述解釋可能迷惑。因為如果禁止 ensureIndex,那么所有的 Index 不會生成,也就不會起效。但是注意這句話的前提條件是第一次創(chuàng)建 Collection 時。也就是說如果在創(chuàng)建 Collection 時,沒有禁止 ensureIndex 那么相應(yīng)的 Index 就會生成,以后即使禁止了 ensureIndex ,已經(jīng)生成的 Index 依然有效。
總結(jié): 在開發(fā)環(huán)境中啟用 ensureIndex ,并且創(chuàng)建 Collection,然后在生產(chǎn)環(huán)境中禁止 ensureIndex 。