1

How to resolve this problem? I always get balance 1000. I want the balance to be 3000.

var checked = [{ _id: '5d96a7ba5ccc6a5850ee5ae7'}, {_id: '5d96a7ba5ccc6a5850ee5ae7' }, {_id: '5d96a7ba5ccc6a5850ee5ae7}];
var income = 1000;

checked.forEach(async x => {

    let balance = CustomerBalanceModel.findOne({user_id: x._id}).exec();

    let balanceValue = {
        balance: (balance + income),
        user_id: x._id,
        updated_at: dateFormatter.date(date)
    }
    await CustomerBalanceModel.findOneAndUpdate({user_id: x._id}, balanceValue, { upsert: true, new: true }).exec();
})

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
ibez
  • 11
  • 2

1 Answers1

1

You forgot to type await before first asynchronous operation:

let balance = await CustomerBalanceModel.findOne({user_id: x._id}).exec(); 

So just add await before CustomerBalanceModel.findOne(...)

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52