Node.js MongoDB创建多个索引:未指定索引名称

Node.js MongoDB创建多个索引:未指定索引名称,node.js,mongodb,indexing,Node.js,Mongodb,Indexing,我使用的是MongoDB版本2.6.11 如何修复此错误?在示例中,您可以传递的唯一参数是索引规范数组和回调函数,我要在哪里指定索引名称?我使用的代码如下(假设我已经需要mongoclient并连接到数据库): 错误代码为67,错误的完整堆栈跟踪如下: MongoError: no index name specified at Function.MongoError.create (/home/ubuntu/workspace/node_modules/mongodb/node_mod

我使用的是MongoDB版本2.6.11

如何修复此错误?在示例中,您可以传递的唯一参数是索引规范数组和回调函数,我要在哪里指定索引名称?我使用的代码如下(假设我已经需要mongoclient并连接到数据库):

错误代码为67,错误的完整堆栈跟踪如下:

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)

我一连接到数据库就运行这个命令。如果数据库是新的,则该集合将不存在,也不会有任何具有指定字段的文档要编制索引,这可能是问题所在吗?

您需要按照说明指定索引

因此,您的调用应该如下所示,为每个索引提供唯一的名称:

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