My query is an array of numbers that I want to pull from a collection. I can map over the array and pull the needed docs, but it will not update the original array (also used spread operator) or save and/or return a new array. I found that Promise.all
something about aggregate
might be solutions, but I am not really sure how to implement. The mongoDB connections are all good and the client request is an array, but an async map
is not practical. How can this be accomplished in a single request?
const Purchase = require('../models/purchase.model')
//Get user purchases
const getPurchases = async(req, res) => {
let purchases = req.body.purchases;
console.log(purchases)
purchases.map(async(p, index) => {
console.log(purchases)
const purchase = await Purchase.findOne({
trans_no: p
})
const purchaseObj = {
date: purchase.date,
total: purchase.total,
merchant_name: purchase.merchant_name,
merchant_id: purchase.merchant_id,
mop: purchase.mop,
items: purchase.items,
trans_no: purchase.trans_no
}
console.log(purchaseObj)
purchases[index] = purchaseObj
})
if (purchases.length > 0) {
return res.json({
status: 'ok',
purchases
})
} else {
return res.json({ status: 'error', purchase: false })
}
}
module.exports = { getPurchases }
CodePudding user response:
You can do it in one request using Purchase.find()
and the $in
keyword. This method will return an array of purchases:
Purchase.find({
'trans_no': { $in: purchases }
}, function(err, docs){
console.log(docs);
});
Your code will be something like:
const Purchase = require('../models/purchase.model')
//Get user purchases
const getPurchases = async(req, res) => {
let purchases = req.body.purchases;
console.log(purchases)
const dbPurchases = await Purchase.find({
'trans_no': { $in: purchases }
});
dbPurchases.map((purchase, index) => {
const purchaseObj = {
date: purchase.date,
total: purchase.total,
merchant_name: purchase.merchant_name,
merchant_id: purchase.merchant_id,
mop: purchase.mop,
items: purchase.items,
trans_no: purchase.trans_no
}
console.log(purchaseObj)
purchases[index] = purchaseObj
})
if (purchases.length > 0) {
return res.json({
status: 'ok',
purchases
})
} else {
return res.json({ status: 'error', purchase: false })
}
}
module.exports = { getPurchases }
You can simplify this code and add a try/catch
to make it more robust :)