I'm currently working on creating an aggregation in MongoDB using NodeJS. The goal is to add an argument to the MongoDB match function if it exists when the resolver function is called. However, I'm encountering an issue where if no addition is made, no results are returned. On the flip side, if there is an addition, the query doesn't come out as expected. Currently, it looks like this:
phaseMatch = 'phase': { $in: CAT,MOD }
. How can I make it look like phaseMatch = 'phase': { $in: ['CAT','MOD'] }
? Is there a way to handle this condition solely within the MongoDB aggregation without involving additional JS code?
async WeeklyTable(_, { batchSize, phase }) {
let res = [];
let phaseMatch = "";
if(phase) phaseMatch = "'phase': { $in: " + phase + " }";
return await collection.aggregate([{
$match: {
"segment": {
$exists: true,
$ne: null
},
phaseMatch
}
}];
}