NodeJS 使用$push和$each将对象追加到数组字段返回null(Mongoose)

whhtz7ly  于 2022-12-03  发布在  Node.js
关注(0)|答案(2)|浏览(168)

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
qeeaahzv

qeeaahzv1#

对嵌入字段使用点“.”表示法

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

r8uurelv2#

原来ID不匹配。代码没有问题。抱歉,伙计们。

相关问题