I just discovered that I can iterate find() in mongoose without using a loop. By doing this.
const arrOfIds = reqBody.items.map(item => item.productId);
Product.find({ '_id': { $in: arrOfIds }},(error, result)=>{
const productList = collect(result).toArray();
})
However my problem is, if there's an id in the array(arrOfIds) that exists more than once, the find() method only treat that as one existence thus that is not correct since I want to sum the prices for this products, duplicate or not.
My previous code was using a map() to loop find() and then calculate sum but got complicated with other codes, I just want simpler method using this one. Can I get it to work to return the document for each IDs, regardless of having duplicates?
let say arrOfIds is ["product1", "product4", "product3", "product1", "product1" ] then you can use below aggregation pls refer to https://mongoplayground.net/p/1DtTtZWCHaH
db.collection.aggregate([
{
"$match": {
_id: {
$in: [
"product1",
"product4",
"product3",
"product1",
"product1"
]
}
}
},
{
"$set": {
"totalPrice": {
"$function": {
"body": "function(arrOfIds,_id,price) {try { var total=0; arrOfIds.forEach((entry) => { if (entry=== _id){total= total+price;}})} catch (e) {row_number= 0;}return total;}",
"args": [
[
"product1",
"product4",
"product3",
"product1",
"product1"
],
"$_id",
"$price"
],
"lang": "js"
}
}
}
}
])
where we match product based on our array and then we set total price based on the number of occurrences using set by implementing function with logic to do for each! its still foreach/loop but on server side