Adam Griffiths
Adam Griffiths

Reputation: 792

Node.js MongoDB creating multiple indexes: no index name specified

I am using MongoDB version 2.6.11

How can I fix this error? In the Node.js API reference the only parameters you can pass are an array of index specifications and a callback function, where am I meant to specify the index names? The code I am using is below (assume I already have required mongoclient and am connected to the database):

db.collection("MyCollection").createIndexes(
    [
        {field1: 1}, 
        {field2: 1, field3: 1}
    ], 
    function(err, result){
        //Error handling code
    }
);

The error code is 67 and the full stack trace for the error is below:

MongoError: no index name specified
    at Function.MongoError.create (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
    at commandCallback (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:1154:66)
    at Callbacks.emit (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:119:3)
    at messageHandler (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:295:23)
    at Socket.dataHandler (/home/ubuntu/workspace/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:285:22)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at Socket.Readable.push (_stream_readable.js:110:10)
    at TCP.onread (net.js:529:20)

I run this command as soon as I connect to the database. If the database is new then that collection will not already exist, nor will any documents with the specified fields to index, could that be the issue?

Upvotes: 2

Views: 2614

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You need to specify the indexes as described here.

So your call should look like this instead to provide a unique name for each index:

db.collection("MyCollection").createIndexes(
    [
        {name: 'field1', key: {field1: 1}}, 
        {name: 'field2_field3', key: {field2: 1, field3: 1}}
    ], 
    function(err, result){
        //Error handling code
    }
);

Upvotes: 3

Related Questions