Home > other >  Array of Object not displaying content after .push()
Array of Object not displaying content after .push()

Time:03-22

I am trying to push object inside array within forEach iteration.

const dashboard_get = async (req, res) => {
    let records = await Record.find();
    let visitors = await Visitor.find();

    let log = {};
    let logs = [];

    records.forEach((record) => {
        visitors.forEach(async (visitor) => {
            if(record.visitor_id === visitor._id.toString()) {
                let establishment = await Establishment.findById({_id:record.establishment_id});
                
                log.id = record.visitor_id;
                log.name = `${visitor.name.fname} ${visitor.name.mi} ${visitor.name.lname}`;
                log.establishment = `${establishment.name}`;
                log.address = `${establishment.address}`;
                log.date = record.createdAt;
            
                logs.push(log);
                //displaying here
                console.log(logs); 
                log = {};
            }
        })  
    })

    // Not displaying here
    console.log(logs); 
    res.render('./Administrator Module/dashboard', {logs});
}

Inside the nested forEach, the logs are displaying correctly. However, I can't access the logs after the forEach. Is pushing of object inside array within forEach will not retain the data?

CodePudding user response:

The issue is, the promise returned by the iteration function is ignored by forEach(). check that Using async/await with a forEach loop

CodePudding user response:

In your code the problem is the declaration of log object outside the for loop.It is all about call by reference and call by value issue. if you move log object inside if condition in nested loop than it will work fine. Do it like this

const dashboard_get = async (req, res) => {
let records = await Record.find();
let visitors = await Visitor.find();
let logs = [];
records.forEach((record) => {
    visitors.forEach(async (visitor) => {
        if (record.visitor_id === visitor._id) {
            let establishment = await Establishment.findById({ _id: record.establishment_id });
            const log = {
                id: record.visitor_id, 
                name: `${visitor.name.fname} ${visitor.name.mi} ${visitor.name.lname}`,
                establishment: establishment.name, 
                address: establishment.address, 
                date: record.createdAt
            };
           
            logs.push(log);
            //displaying here
            console.log(logs);
        }
    })
});

// Not displaying here
console.log(logs);
res.render('./Administrator Module/dashboard', { logs });
}
  • Related