Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

0

You can try for await

for await (variable of iterable) { statement }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!