I'm trying to update a particular field in a user row, and I'm using a forEach loop to do this, but it's only the last loop to run that gets updated. here's how my code looks:
const UserSchema = require('../models/UserSchema');
const updates = [100, 200];
const userID = req.user.id;
updates.forEach(update => {
UserSchema.findByID(userID).then(user => {
user.balance += update;
user.save.then(user => console.log('user balance updated'));
})
})
After running this code, the user's balance should be '300', but instead it's '200'..it's like the last one to run overwrites the first one because they're running at very close intervals, i can;t just wrap my head around this...please what's the solution?