简体   繁体   中英

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?

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')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM