Node.js MongoDB创build多个索引:没有指定索引名称

我正在使用MongoDB 2.6.11版本

我该如何解决这个错误? 在Node.js API参考中 ,您可以传递的唯一参数是一个索引规格数组和一个callback函数,我的意思是指定索引名称? 我正在使用的代码是下面(假设我已经有需要mongoclient和连接到数据库):

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

错误代码是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 } );