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

170
Visualizações
Looping over objects to add property not working (Javascript with Mongodb)

I want to grab a list of all the users, compare the list to a survey database to see how many votes each one of them has received, and append those vote values to the user object, and send back to the front.

I read examples on SO like this: 'TypeError: meme.find(...).forEach is not a function' in mongoose node js? and this: Adding Properties in a forEach Loop in Mongoose

I'm trying to do the same thing.

I have simple code, but it doesn't work.

Attempt #1:

let users = await User.find({teams: {$in: req.user.team_oid}}, {_id: 1, firstname: 1, lastname: 1})

users.forEach(async(user, i) => {

    let nomineeCount = await Survey.countDocuments({_id: mongoose.Types.ObjectId(req.params.s_oid), 'facilitators.nominee': mongoose.Types.ObjectId(user._id) })

    user["votes"] = nomineeCount;

    if(i+1 === users.length) {res.json({users: users})}
})

The queries and everything is working, except the user does not receive the ["votes"] property.

Attempt #2:

let users = await User.find({teams: {$in: req.user.team_oid}}, {_id: 1, firstname: 1, lastname: 1})

let nominees = users;

users.map( async (user, i) => {

let nomineeCount = await Survey.countDocuments({_id: mongoose.Types.ObjectId(req.params.s_oid), 'facilitators.nominee': mongoose.Types.ObjectId(user._id) })

    nominees[i].votes = nomineeCount;
        
    if(i+1 === nominees.length) {res.json({users: nominees})}
})

This also fails to attach the .votes property.

Any ideas / suggestions appreciated.

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

0

You can try for await

for await (variable of iterable) { statement }

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