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条答案
按热度按时间qeeaahzv1#
对嵌入字段使用点“.”表示法
r8uurelv2#
原来ID不匹配。代码没有问题。抱歉,伙计们。