From 0375d6ddd2282f0b61cab47e8f4ff90c295290c3 Mon Sep 17 00:00:00 2001 From: mrbontor Date: Mon, 27 Feb 2023 06:43:33 +0700 Subject: [PATCH] feat(aggregation): allow to filter/search in sub collections --- libs/generateAgregation.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/libs/generateAgregation.js b/libs/generateAgregation.js index 0ab825c..f26f73b 100644 --- a/libs/generateAgregation.js +++ b/libs/generateAgregation.js @@ -5,16 +5,14 @@ const { ValidateAgregation } = require('./validation'); * @param {Object} query * @param {string} query.collectionName * @param {string} query.uniqueId + * @param {string} query.subSearch + * @param {Array} query.fieldToSearch * @returns */ const pipeline = (query) => { - const { collectionName, uniqueId, projection } = query; + const { collectionName, uniqueId, subSearch, fieldToSearch } = query; - /** - * TODO - * - custom on `pipeline` (join stage), it doesnt always have to do _query_ `$match` instead using `foreignField` - */ - return [ + const queryLookup = [ { $lookup: { from: collectionName, @@ -30,6 +28,24 @@ const pipeline = (query) => { } } ]; + if (subSearch && fieldToSearch && fieldToSearch.length > 0) { + const newearch = fieldToSearch.map((el) => { + const key = `${uniqueId}.${el}`; + return { + [key]: { + $regex: subSearch, + $options: 'i' + } + }; + }); + queryLookup.push({ + $match: { + $or: newearch + } + }); + } + + return queryLookup; }; /**