@joktec/mongo
Version:
JokTec - Mongo Service
69 lines • 2.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongoPipeline = void 0;
const utils_1 = require("@joktec/utils");
const typegoose_1 = require("@typegoose/typegoose");
const lodash_1 = require("lodash");
const mongo_helper_1 = require("./mongo.helper");
class MongoPipeline {
static match(condition) {
return mongo_helper_1.MongoHelper.parseFilter(condition);
}
static search(keyword) {
return { $text: { $search: keyword } };
}
static near(near) {
return Object.keys(near).map(path => {
const { lat, lng, distance } = near[path];
return {
distanceField: `${path}Distance`,
near: { type: 'Point', coordinates: [lng, lat] },
maxDistance: (0, utils_1.toInt)(distance, 1000),
query: {
[path]: {
$nearSphere: {
$geometry: {
type: 'Point',
coordinates: [lng, lat],
},
$maxDistance: (0, utils_1.toInt)(distance, 1000),
},
},
},
};
});
}
static sort(sort) {
return mongo_helper_1.MongoHelper.parseSort(sort);
}
static projection(select) {
return mongo_helper_1.MongoHelper.parseProjection(select);
}
static lookup(populate, model) {
const populateOptions = mongo_helper_1.MongoHelper.parsePopulate(populate);
return populateOptions.flatMap(populate => {
const { path, options } = model.schema.virtuals[populate.path];
const { ref, foreignField, localField, justOne } = options;
const refCollection = (0, typegoose_1.getModelWithString)(ref).collection.collectionName;
const lookup = {
from: refCollection,
localField: localField,
foreignField: foreignField,
as: path,
};
const subPipelines = [];
if (!(0, lodash_1.isEmpty)(populate.match))
subPipelines.push({ $match: populate.match });
if (populate.select)
subPipelines.push({ $project: populate.select });
if (subPipelines.length)
lookup.pipeline = subPipelines;
const pipelines = [{ $lookup: lookup }];
if (justOne)
pipelines.push({ $addFields: { [path]: { $arrayElemAt: [`$${path}`, 0] } } });
return pipelines;
});
}
}
exports.MongoPipeline = MongoPipeline;
//# sourceMappingURL=mongo.pipeline.js.map