Should the createIndex () function be called every time the database gets connected like given here in the tutorial http://mongodb.github.io/node-mongodb-native/2.1/tutorials/geospatial-search/ If using geospatial indices do I need to call the function every time?
According to the docs:
The createIndex() method only creates an index if an index of the same specification does not already exist.
This applies to geospatial indexes as well.
About where to do it, since you only need to execute it once, in general it's not necessary to include this operation in your app server code.
I can think of two options about how to execute it:
createIndex()
directly through the MongoDB ClientAbout when to do it, indexes can be created at any moment, but doing it before you insert data in that collection is recommended.
I for example call createIndex()
after I established a connection with the mongoDBClient like so:
private connectionManager: MongoClient;
public connect(): Promise<void| string> {
return this.mongoClient.connect()
.then((mongoClient: MongoClient) => this.connectionManager = mongoClient)
.then(() => this.setupDBIndexes())
.catch((e: Error) => console.log('Could not connect to mongo server: ' + e));
}
private setupDBIndexes() {
return this.connectionManager.db('users').collection('list').createIndex( {"email": 1} as Object, {unique: true})
}
connect()
is called on the lifecycle begin of the app. I am curios if this is also an option or there are way better alternatives. What I am thinking at least, is to call createIndex()
on every insert operation seems really wrong.
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