Reputation: 2622
I'm building an object-of-arrays via multiple data-base queries in a single router.get() with Express & Node.
To do this I need to: (1) query a collection, (2) append the results to an object, (3) pass the object through middleware using next(), (4) repeats quite a few times, (5) end with a nifty object that has multiple arrays attached.
Here's the pattern I'm using (just one example):
}, (req, res, next) => {
let { checkBoosters } = req;
let boosterNo = [];
let boosterMoGo = [];
if(!checkBoosters.checkBoosters.length){
return next()
}
//re-check boosters (from sentry)
for(let i=0; i<checkBoosters.checkBoosters.length; i++){
Phases.find({name: "Booster", team_oid: checkBoosters.checkBoosters[i]._id, weeks: {$gt: 0}}, (err, doc) => {
if(!doc.length){
boosterNo.push(doc[0])
}
if(doc.length){
boosterMoGo.push(doc[0])
}
if(checkBoosters.checkBoosters.length == i+1){
res.locals.boosterMoGo = { boosterMoGo }
req.boosterNo = { boosterNo }
return next()
}
})
}
}, (req, res, next) => {
This basically works, but you may have already noticed my problem...
Thanks for any help you can offer.
Upvotes: 1
Views: 640
Reputation: 4176
res.locals
is the preferred way of doing this, see also this SO answer.checkBoosters.checkBoosters
type object patterns is because you assign using req.checkBoosters = { checkBoosters }
while req.checkBoosters = checkBoosters
would give you your desired result (without constructing a new object with the redundant property checkBoosters
).Upvotes: 1