SCBuergel
SCBuergel

Reputation: 1653

nodejs + mongodb: Modify existing document

I store balances of users in mongo. Now I want to mathematically add to an existing balance as in balance = balance + amount. I am looping over multiple values in a function which gets an array of balances that are to be updated. The following

UserModel.findOneAndUpdate({ address: accounts[c].address }, 
  { balance: accounts[c].amount }, 
  (error, user) => { 
    // do stuff
  }
);

What I want is something like:

  { balance: user.amount + accounts[c].amount }, 

I also tried to first read the value and in the callback function do another findOneAndUpdate, unfortunately the callback handler does not have the right index c and thus accesses the wrong element in accounts[c].amount.

Upvotes: 0

Views: 47

Answers (1)

Emin Laletovic
Emin Laletovic

Reputation: 4324

Instead { balance: accounts[c].amount } try { $inc: { balance: accounts[c].amount }}. It should just increment balance by accounts[c].amount.

Upvotes: 1

Related Questions