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.