Mongoose复合索引未创建(太长)

6

我在MongoDB的一个模式上创建多个复合索引时遇到了一些问题。使用MongoLab时,我知道当索引名称太长时,由于命名问题,某些索引不会被创建。因此,我怀疑这可能是某些索引未被创建的原因。

var Schema = new mongoose.Schema({ ... });

// Created
Schema.index({
    one: 1,
    three: 1
});

// Not Created
Schema.index({
    one: 1,
    two: 1,
    three: 1,
    four: 1,
    five: 1,
    six: 1,
    seven: 1,
    eight: 1,
    nine: 1,
    ten: 1
});

创建第二个索引时,它是否会在屏幕上打印出任何内容? 你怎么知道第二个索引没有被创建?你在Mongo shell中检查过吗? - somallg
@somallg 我还没有添加任何日志记录。我检查了Mongo shell,它并没有被创建,这就是我知道的原因。当我手动尝试创建该索引时,我会得到以下提示:"MongoDB生成的默认索引名称太长,请指定自定义名称。" - woutr_be
1
没错,MongoDB默认索引名称是有限制的(https://docs.mongodb.org/manual/reference/limits/#Index-Name-Length)。 您可以通过向Schema.index传递附加选项来指定自定义名称 Schema.index({ one: 1, two: 1, three: 1, four: 1, five: 1, six: 1, seven: 1, eight: 1, nine: 1, ten: 1 }, { name: 'my_index_name' } ); - somallg
谢谢,这正是我正在寻找的。 - woutr_be
@somallg,你能把那个作为答案添加吗?这样我就可以标记它为已解决。 - woutr_be
1个回答

8

默认索引名称有限制(https://docs.mongodb.org/manual/reference/limits/#Index-Name-Length),需要注意。

可以通过向 Schema.index 传递附加选项对象来指定自定义索引名称。

Schema.index({
    one: 1,
    two: 1,
    three: 1,
    four: 1,
    five: 1,
    six: 1,
    seven: 1,
    eight: 1,
    nine: 1,
    ten: 1 }, 
    { name: 'my_index_name' }
);

“默认情况下,**<索引名称>是字段名称和索引类型的连接。** 您可以显式地指定createIndex()方法中的<索引名称>,以确保完全限定的索引名称不超过限制。” “完全限定的索引名称包括命名空间和点分隔符(即<数据库名称> . <集合名称> . $ <索引名称>),长度不能超过128个字符。 - Константин Ван

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接