0

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.

2
  • Just to make it clear, you want to update balance field with accounts[c].amount? Commented Feb 24, 2017 at 15:37
  • no, I want to add the amount. as in balance = balance + accounts[c].amount. NB: With add I mean the mathematical operation on numbers, not adding an element. Commented Feb 24, 2017 at 15:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.