Skip to content

Commit c61ecd7

Browse files
refactor(plugin): separate casting logic from plugin
1 parent d911ab1 commit c61ecd7

File tree

3 files changed

+43
-33
lines changed

3 files changed

+43
-33
lines changed

index.js

+1-33
Original file line numberDiff line numberDiff line change
@@ -1,33 +1 @@
1-
const { Query } = require('mongoose');
2-
const mongooseQuery = new Query();
3-
4-
const stagesThatDoNotAffectProjection = Object.freeze(['$match', '$limit', '$sort', '$skip', '$sample']);
5-
6-
function aggregationCastPlugin (schema) {
7-
schema.pre('aggregate', function (next) {
8-
const pipeline = this.pipeline();
9-
10-
11-
for (let i = 0; i < pipeline.length; i++) {
12-
const stage = pipeline[i];
13-
const stageName = getStageName(stage);
14-
15-
const projectionHasChanged = !stagesThatDoNotAffectProjection.includes(stageName);
16-
if (projectionHasChanged) return next();
17-
18-
if (stageName === '$match') stage[stageName] = castFilter(this._model, stage[stageName]);
19-
}
20-
21-
next();
22-
});
23-
}
24-
25-
function getStageName (stage) {
26-
return Object.keys(stage)[0];
27-
}
28-
29-
function castFilter (Model, filter) {
30-
return mongooseQuery.cast(Model, filter);
31-
}
32-
33-
module.exports = aggregationCastPlugin;
1+
module.exports = require('./lib');

lib/cast.pipeline.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const { Query } = require('mongoose');
2+
const mongooseQuery = new Query();
3+
4+
const stagesThatDoNotAffectProjection = Object.freeze(['$match', '$limit', '$sort', '$skip', '$sample']);
5+
6+
function castPipeline (model, pipeline) {
7+
for (const stage of pipeline) {
8+
const stageName = getStageName(stage);
9+
10+
if (stageName === '$geoNear' && stage.$geoNear.query) {
11+
castFilter(model, stage.$geoNear.query);
12+
}
13+
14+
const projectionHasChanged = !stagesThatDoNotAffectProjection.includes(stageName);
15+
if (projectionHasChanged) {
16+
return;
17+
}
18+
19+
if (stageName === '$match') stage[stageName] = castFilter(model, stage[stageName]);
20+
}
21+
}
22+
23+
function getStageName (stage) {
24+
return Object.keys(stage)[0];
25+
}
26+
27+
function castFilter (Model, filter) {
28+
return mongooseQuery.cast(Model, filter);
29+
}
30+
31+
module.exports = castPipeline;

lib/index.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const castPipeline = require('./cast.pipeline');
2+
3+
function castAggregationPlugin (schema) {
4+
schema.pre('aggregate', function () {
5+
const pipeline = this.pipeline();
6+
7+
castPipeline(this._model, pipeline);
8+
});
9+
}
10+
11+
module.exports = castAggregationPlugin;

0 commit comments

Comments
 (0)