【问题标题】:Node.js MongoDB creating multiple indexes: no index name specifiedNode.js MongoDB 创建多个索引:未指定索引名称
【发布时间】:2016-05-08 14:36:56
【问题描述】:

我使用的是 MongoDB 版本 2.6.11

如何解决此错误?在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)

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

【问题讨论】:

    标签: node.js mongodb indexing


    【解决方案1】:

    您需要按照here 的描述指定索引。

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 2020-07-25
      • 2016-05-25
      • 2011-08-20
      • 1970-01-01
      相关资源
      最近更新 更多