Home > Net >  Appending objects to array field using $push and $each returns null (Mongoose)
Appending objects to array field using $push and $each returns null (Mongoose)

Time:12-03

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

CodePudding user response:

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)
})

CodePudding user response:

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

  • Related