Derrick Mcmillen
Derrick Mcmillen

Reputation: 51

mongo native ensureIndex does not create index

I am using the mongodb native driver for node. I call ensureIndex({ keywords: 1}) after retrieving the collection. When I check in the mongo console, nothing appears when I call db.mycol.getIndexes().

What am I doing wrong?

Upvotes: 5

Views: 4762

Answers (2)

fsaint
fsaint

Reputation: 8759

I encountered a similar problem and the problem was I was not opening the database before calling ensureIndex. What I was doing was (coffee script)

db.collection('resources').ensureIndex {"$**": "text"}, {name: "email_index_text"},(err, indexName) ->
        console.log indexName
        console.log err
        db.close()

and what worked was

db.open (err,database) ->
    db.collection('resources').ensureIndex {"$**": "text"}, {name: "email_index_text"},(err, indexName) ->
        console.log indexName
        console.log err
        db.close()

The first snippet did nothing at all. No index was created and no error thrown.

Upvotes: 0

Alex
Alex

Reputation: 38499

The API docs helped a little: http://mongodb.github.com/node-mongodb-native/api-generated/db.html#ensureindex

You're supposed to call ensureIndex on the database object, not the collection. This contradicts the JavaScript console.

Upvotes: 2

Related Questions