Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

0

You can try for await

for await (variable of iterable) { statement }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda