Mongoose Index Field Creation Order

I have a question about creating a composite index in mongodb: Let's say I want to create this composite index:

cSchema.index({account:1, authorization: 1, c_type: 1});

      

The problem is that javascript doesn't guarantee the order of the dictionary, so I'm not sure if the composite index is in the order I want.

How can I be sure that it is really {account:1, authorization:1, c_type:1}

in this order?

Thank!

+3


source to share


1 answer


The simple answer is that most people abuse the fact that simple String properties that do not parse an integer on an object will be listed in the order of creation. While not guaranteed in ES2015 for some enumeration methods , it works in a limited environment like Node / V8. This worked in most JS engines for a while, but was never part of the ES spec until ES2015.

MongoDB

The supporting MongoDB driver createIndex

supports String

, Array

and Object

index definitions. The parsing code is in a utility function called parseIndexOptions

.

If you specify an array of strings, pairs of arrays or objects, then the order will be corrected:

['location','type']
[['location', '2d'],['type', 1]]
[{location: '2d'},{type: 1}]

      



Also note what the code createIndex

uses Object.keys

to enumerate when it gets the Object

index properties.

Mongoose

The function is Schema#index

documented as requiring the object to go to the "MongoDB driver createIndex()

" function , so it looks to support passing through whatever options you provide.

There are several places where indexes are further processed. For example, if you are creating a subdocument with an index, the index must have a parent schema, prefixed with the field names . With a quick glance, I think this code still works with an array, but I don't see any tests for this in Mongoose's code, so you can validate it yourself.

Mongoose has a complex index test that depends on the order of object properties .

+1


source







All Articles