1

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...

  1. I can't decide if I should be using the "req" or the "res.locals" to store these arrays?
  2. The object is getting "checkBoosters.checkBoosters" type object patterns. Can I avoid this?

Thanks for any help you can offer.

etarhan
  • 4,138
  • 2
  • 15
  • 29
Izzi
  • 2,184
  • 1
  • 16
  • 26

1 Answers1

1
  1. When passing data between middleware the general consensus seems to be that res.locals is the preferred way of doing this, see also this SO answer.
  2. As for your second question the main reason you get 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).
Izzi
  • 2,184
  • 1
  • 16
  • 26
etarhan
  • 4,138
  • 2
  • 15
  • 29
  • Thanks @etarhan - that perfectly answered my questions. I'm still curious about the trade-offs between res.locals & req. I had a senior dev teach me the req approach, so I was defaulting to that, but I agree that all of the SO answers I've seen use the res.locals approach. Cheers. – Izzi Aug 25 '20 at 06:21