3

I have a mongo db where I have create a record that has an object within an array (e.g. employees: [{name:Bob, Age: 30}]. I now want to update the object within the array so it looks like [{name:Bob, age: 30, pay:400}]. How do I do this within a node/express route? If I use something like:

router.put("/addPay/:id",function(req,res){
Team.findByIdAndUpdate(req.params.id,{$push:{employee: {$each: 
[{pay:req.body.pay}]}}},........

this just pushes {pay: XXX} as a separate object into the array [{name:Bob, age: 30, pay:400}, {pay: XXX}] rather than inserting it into the object already there. I know there are plenty of questions about pushing into objects and arrays etc on SO but I couldn't find a similar example to this situation. Thanks!

5
  • Does req.body contain employee's name ? Commented Feb 4, 2019 at 21:19
  • No its the pay amount (e.g. 400). If I console.log it, I get the value passed through from my form so that works... Commented Feb 4, 2019 at 21:21
  • So how do you know which employee should have this value set ? Do you have always one value in that array ? Commented Feb 4, 2019 at 21:22
  • yes exactly - just the one employee. The model Schema I am using is actualluy more complicated than this - i just made this to get the heart of my problem. Commented Feb 4, 2019 at 21:24
  • Okay, then the answer provided by @cowCrazy should be fine for you, just use employee.0.pay Commented Feb 4, 2019 at 21:27

1 Answer 1

1

You need to have the index of the object you want to change, then you write it like this:

'array.index.keyToUpdate'.

If you have the index of the object before the update operation you can do it like this:

{$set: { 'employee.<indexToChange>.pay': 400 }}.

To make it dynamic and based on the query you can do:

update({ 'employee.name': 'Bob' }, {$set: { 'employee.$.pay': 400 }}).

In this case the $ stands for the first matched object in the array.

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.