Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
Array of Object not displaying content after .push()

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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 });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda