Izzi
Izzi

Reputation: 2622

res.local to pass array through Express

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.

Upvotes: 1

Views: 640

Answers (1)

etarhan
etarhan

Reputation: 4176

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

Upvotes: 1

Related Questions