Jarvis
Jarvis

Reputation: 45

How to update multiple arrays in a document?

Given a mongoose schema like I am trying to use this POST to get the current price of a stock and match it to a user's balance. If the stock is less then the user balance then it should be subtracted from the balance. Once done the portfolio should update the total amount of shares if a user owns it and push a transaction to the users array.

var UserSchema = new mongoose.Schema({
    email : { type: String, unique: true, required: true, trim: true},
    name  : { type: String, required: true},
    password : { type: String, required: true},
    balance : {type: Number, default: 5000},
    transactions : [
        {
            name : { type: String, required: true},
            buy_or_sell : {type: Boolean, required: true},
            shares : {type: Number, required: true},
            value : {type: Number, required: true}
        }
    ],
    portfolio : [
        {
            name : { type: String, unique: true, required: true },
            shares : { type: Number, required: true }
        }
    ]

});
router.post('/portfolio', (req, res, next)=>{
  if (req.session.userId !== undefined){

    var ticker = (req.body.ticker).toLowerCase();
    var qty = req.body.qty;

    User.findOne({ _id: req.session.userId }).exec(async function(err, user) {
      var balance = user.balance;
      const data = await alpha.data.quote(`${ticker}`);
      var sum = Number((data['Global Quote']['05. price'] * qty).toFixed(2));
      if (sum < balance){
        let total = Number(balance-sum).toFixed(2)
        let doc = await User.findOneAndUpdate({_id: req.session.userId}, {balance : sum})
        ....
        ....
      }
    });

  } else {
    res.redirect('/')
  }

});

Upvotes: 0

Views: 162

Answers (1)

Thom
Thom

Reputation: 1623

In the same query you can update several field of a document. To add a new entry to an array use $push. To update a specific element of an array it is more tricky, you need to use $set and $ with a filter to know which element to update.

Something like that should do the trick:

await User.findOneAndUpdate(
    {
        _id: req.session.userId,
        portfolio.name 'indicateHereThePortfolioNameYouWantToUpdate'
    }, 
    {
        $push: {transactions: transactionToAdd}
        $set: {
            balance: sum,
            portfolio.$.shares: newShareValue
        }
    });

Upvotes: 1

Related Questions