There is a better way to get the desired result with MongoDB and no need to loop, use the aggregation framework where you can run the following pipeline which uses $facet
as
try {
const array = ["brunch", "lunch", "crunch"]
const facet = array.reduce((acc, cur) => {
acc[cur] = [{ "$match": { "category": cur } }]
return acc
}, {})
const pipeline = [
{ "$match": { "category": { "$in": array } } },
{ "$facet": facet }
]
const results = await Venue.aggregate(pipeline).exec()
const data = results[0]
return data
} catch(err) {
throw err
}
You can also group the documents by the category key and $push
the documents per group and then convert into keys of a document in a $replaceRoot
with $arrayToObject
try {
const array = ["brunch", "lunch", "crunch"]
const pipeline = [
{ "$match": { "category": { "$in": array } } },
{ "$group": {
"_id": "$category",
"data": { "$push": "$$ROOT" }
} },
{ "$group": {
"_id": null,
"venues": {
"$push": {
"k": "$_id",
"v": "$data"
}
}
} },
{ "$replaceRoot": {
"newRoot": { "$arrayToObject": "$venues" }
} }
]
const results = await Venue.aggregate(pipeline).exec()
const data = results[0]
return data
} catch(err) {
throw err
}