Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where, when and how many times to call the createIndex function when using node.js and mongodb

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?

like image 240
user1261913 Avatar asked Oct 14 '25 03:10

user1261913


2 Answers

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:

  • Creating an script in Node.js using the code you pointed out (I like this method since it's safer in general, you can create tests, etc)
  • Executing createIndex() directly through the MongoDB Client

About when to do it, indexes can be created at any moment, but doing it before you insert data in that collection is recommended.

like image 54
Antonio Val Avatar answered Oct 16 '25 16:10

Antonio Val


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.

like image 45
MarcoLe Avatar answered Oct 16 '25 17:10

MarcoLe