Search code examples
node.jsmongodbexpressmongoose-schema

How can i simultenously update the same field in a MongoDB Record?


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?


Solution

  • You are dealing with an async loop here, but the code doesn't wait for the promises to complete before moving onto the next.

    It's much easier using an async function.

    async function updateBalances(userID, updates){
        for (const update of updates) {
          const user = await UserSchema.findByID(userID)
          user.balance += update
          await user.save()
        }
        console.log('user balances updated')
    }