如何在node.js中为MongoDB索引指定javascript对象中属性的顺序?

MongoDB documentation声明:

For indexes with more than one key (i.e. compound indexes) the sequence of fields is important.

但ECMAScript定义了一个对象如下:

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function.

在node.js中使用MongoDB时(例如使用this module),您使用的是服务器端javascript,如下例所示.

当MongoDB期望一个对象(AKA无序的属性集合)时,如何指定序列?

collection.ensureIndex({
    date    : -1,
    client  : 1,
    product : 1
});

解决方法:

在MongoDB中,文档中字段的顺序确实很重要,并且所有语言驱动程序都提供了一种指定文档的方法,即使底层编程语言没有这样的概念.

MongoDB在其shell中使用的文档格式类似于JSON,但不是严格的JSON.除其他外,始终保留字段顺序.

在Javascript中,标准将字段定义为无序,因此实现可以*忽略/不保留排序.但实际上,所有实现都会保留排序.特别是V8引擎保留了订单,这是node.js中使用的引擎,所以没问题.

上一篇:python – TypeError:’float’对象不可订阅


下一篇:java – String类中的子串方法到达不应该的索引