LearnBoost/mongoose — pull request #2451 by yamadapc (2014-11-10 02:04:08+00:00)
Title: Fix aggregation on discriminator models

When performing aggregations over discriminator models, one would expect
the same semantics of performing queries over discriminator models would
apply. That's not the case, however, and no extra query limiting the
aggregation pipeline to a discriminator's type is added to the pipeline.

This adds tests for that feature to the
`test/model.discriminator.querying.test.js`, which test for those
semantics in the `Query` logic (it didn't seem appropriate to add
another test file).

It also adds an implementation of the feature, which borrows from the
`lib/query.js` module's `prepareDiscriminatorCriteria` helper function,
adding a `$match` stage to the top of the pipeline, when there's a
non-root discriminator model.

The filtering is only added to the pipeline just before calling `exec`
over `model.collection.aggregate`, so empty pipelines will still look
empty even if this is added (`Model.aggregate().exec()` still throws
instead of executing an empty pipeline).

It also merges the added stage onto the first pipeline stage if it's a
`$match` group and has no discriminator key in it. This allows (I think)
for query optimization to happen on the `match` stage.

It should be noted that if a discriminator key does exist on the first
`$match`, the discriminator filter will be added before the existing
pipeline, rather than overwriting the existing one - which will yes,
lead to two queries which will never yield any value. This is better
than overwriting the existing one or simply not adding anything because
it's more consistent with the idea of a discriminator.

I'll be glad to provide examples if this isn't clear enough or make
whatever changes you think will make the code cleaner.