1

I'm making an app with Node.js and Express. I have the following in one of my routes files:

router.get('/', (req, res) => {
Manufacturer.find({}, (err, manufacturers) => {
    if(err) {
        console.log(err)
        req.flash('error', 'No manufacturers were found')
        res.redirect('/')
    }

    let allAircrafts = {"manufacturers": {}}

    for(let key in manufacturers) {
        let currentManufacturerAircrafts = []
        let manufacturerName = manufacturers[key].name

        Aircraft.find({manufacturer_name: manufacturerName}, (err, aircrafts) => {
            if(err) {
                console.log(err)
                req.flash('error', 'No aircrafts were found')
                res.redirect('/')
            }

            for(let akey in aircrafts) {
                currentManufacturerAircrafts.push(aircrafts[akey])
            }

            // let manufacturerObj = {name: manufacturerName, aircrafts: currentManufacturerAircrafts}
            allAircrafts["manufacturers"][manufacturerName] = currentManufacturerAircrafts

           // console.log(allAircrafts) #1
        })
    }
         // console.log(allAircrafts) #2
    res.render('aircrafts', { expressFlash: req.flash(), sessionFlash: res.locals.sessionFlash, allAircrafts})        
})
})

The allAircrafts object is supposed to store all the aircrafts from all the manufacturers and when I console.log it below (in #1) it really does work and I get the expected value. When I console.log it in #2 I only get this:

{ manufacturers: {} }

I have no idea why it's showing me this, but I suspect that it's not saving it properly.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

0 Answers0