1

Background: I have an array (A) of new objects that need to be added to an array field in Mongoose. if successful it should print to screen the newly updated object but it prints null. I checked the database and confirmed it also does not update at all. I followed the docs to use the $push and $each modifiers here: https://www.mongodb.com/docs/manual/reference/operator/update/each/

Desired Behaviour: I would like each object in (A) to be added to the Array field, not (A) itself. Upon success, it should print to screen the newly updated object.

Attempted Approach:

let identifier={customer:{external_id:'12345'}}
let array = [{value:30},{value:30}]
User.findOneAndUpdate(identifier,{$push:{points:{$each:array}}},{new:true})
.then((result)=>{
console.log(result)
})

Attempted Resolutions:

  • I tested if the issue was with the identifier parameter, but it works fine when the update parameter does not have $each (i.e. it pushes the whole array (A) into the array field)
  • I thought about using $addToSet like in the solution below, but as you can see in the sample code above, I want to push all objects even if they are not unique: Mongoose - Push objects into nested array

2 Answers 2

0

use dot "." notation for embedded field

let filter={'customer.external_id':'12345'}

let array = [{value:30},{value:30}];

let update = { $push: { points: { $each: array } } };


User.findOneAndUpdate(filter,update,{new: true})
.then((result)=>{
     console.log(result)
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the comment. I updated it to dot notation but it still returns null.
please show your sample document
0

It turns out the IDs did not match. There was no issue with the code. Sorry guys.

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.