2016-05-08 73 views
2

我使用的是MongoDB 2.6.11版本Node.js MongoDB創建多個索引:沒有指定索引名

我該如何解決這個錯誤?在Node.js API reference中,您可以傳遞的唯一參數是一個索引規範數組和一個回調函數,我的意思是指定索引名稱?我使用的代碼如下(假設我已經要求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) 

我一連接到數據庫就運行此命令。如果數據庫是新的,那麼這個集合將不會存在,任何具有指定字段索引的文檔都可能成爲問題?

回答

2

您需要指定here所述的索引。

所以你的電話應該是這樣的,而不是爲每個指標提供了一個獨特的名字:

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