mongoose-atlas-search
Version:
A customisable mongoose plugin to use MongoDB Atlas Search feature
62 lines • 2.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAggregationQuery = exports.validateOptions = exports.defaultSearchFunction = void 0;
const defaultSearchFunction = (query, path) => {
return {
text: {
query,
path,
},
};
};
exports.defaultSearchFunction = defaultSearchFunction;
const validateOptions = (options) => {
if (!options.model)
throw new Error('options.model is required!');
if (!options.searchFunction && !options.path)
throw new Error('options.path or options.searchFunction is required!');
return {
path: options.path,
model: options.model,
searchFunction: options.searchFunction || exports.defaultSearchFunction,
searchKey: options.searchKey || 'search',
overwriteFind: !!options.overwriteFind,
addFields: options.addFields,
};
};
exports.validateOptions = validateOptions;
const buildAggregationQuery = (query, projection, queryOptions, options) => {
const { searchFunction, path, searchKey, addFields } = options;
const aggregationQuery = [];
const searchStep = { $search: searchFunction(query[searchKey], path, query) };
aggregationQuery.push(searchStep);
const matchStep = { $match: {} };
Object.keys(query).forEach((key) => {
if (key !== searchKey)
matchStep.$match[key] = query[key];
});
aggregationQuery.push(matchStep);
const addFieldsStep = queryOptions.sort ? { $addFields: { score: { $meta: 'searchScore' } } } : {};
if (addFields) {
addFieldsStep.$addFields = { ...addFieldsStep.$addFields, ...addFields };
}
if (Object.keys(addFieldsStep).length)
aggregationQuery.push(addFieldsStep);
if (queryOptions.sort) {
aggregationQuery.push({ $sort: { ...queryOptions.sort, score: -1, _id: 1 } });
}
if (queryOptions.skip) {
aggregationQuery.push({ $skip: queryOptions.skip });
}
if (queryOptions.limit) {
aggregationQuery.push({ $limit: queryOptions.limit });
}
if (projection) {
aggregationQuery.push({
$project: projection,
});
}
return aggregationQuery;
};
exports.buildAggregationQuery = buildAggregationQuery;
//# sourceMappingURL=utils.js.map