0

I have a Mongoose schema here:

const assetSchema = new mongoose.Schema({
  symbol: String,
  amount: Number
})

const userSchema = new mongoose.Schema({
    user: String,
    budget: Number,
    assets: [assetSchema]
  })

I try to use it to simulate stock trading. I have users in database and their stocks record in an array. Like this:

{
"user": "John", 
"budget": 10000, 
"assets": [{"symbol":"TSLA", "amount": 5}, {"symbol":"AAPL", "amount": 10}, ........ ]
}

How can I find a particular object in assets array by its symbol, and update it? {"symbol":"TSLA", "amount": 20} for example. or how to redesign my schema would be better?

2
  • From the marked duplicate answers, use the positional operator in your update e.g. await User.findOneAndUpdate({ user: 'John', 'assets.symbol': 'TSLA' }, { $set: { 'assets.$.amount': 20 } }).exec() Commented Dec 1, 2020 at 13:10
  • 1
    Thank you, it works!! @chridam Commented Dec 1, 2020 at 16:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.