Snowball
Snowball

Reputation: 1512

Mongoose discriminator and indexes

If I setup a Model with a discriminator key mongoose automatically prefixes all queries with the discriminator key.

But if I define some keys as index: true the indexes that are created are not prefixed by the discriminator key. Instead they are simple indexes with a single key.

Isn't this suboptimal? Shouldn't all indexes be compound indexes of the discriminatorKey (e.G. __t) and the key I want to index?

And if yes should I instead of defining indexes at the path level (via index: true) prefer to set them like this:

Event.index({ __t: 1, type: 1 });

Upvotes: 2

Views: 1847

Answers (1)

japrescott
japrescott

Reputation: 5023

no its not suboptimal. The discriminator key makes mongoose understand which schema/model you are using and creates an instance of one for you automatically when eg. a query comes back. Mongoose doesn't know how you will be using that additional key (maybe you want to query all of your types for a specific value? or you want to make a unique index on a name over all your types?), so creating 'basic' indexes via the path value just does what you describe, it just makes an index.

if you have the usecase that these are strongly linked, you can create compound index or sparse indexes.

Upvotes: 1

Related Questions