简体   繁体   English

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

[英]Appending objects to array field using $push and $each returns null (Mongoose)

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.背景:我有一个新对象数组 (A) 需要添加到 Mongoose 中的数组字段。如果成功,它应该打印以筛选新更新的 object,但它打印 null。我检查了数据库并确认它也没有完全更新。 I followed the docs to use the $push and $each modifiers here: https://www.mongodb.com/docs/manual/reference/operator/update/each/我按照文档在这里使用 $push 和 $each 修饰符: 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.期望的行为:我希望将 (A) 中的每个 object 添加到数组字段,而不是 (A) 本身。 Upon success, it should print to screen the newly updated object.成功后,它应该打印以筛选新更新的 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 (ie it pushes the whole array (A) into the array field)我测试了问题是否与标识符参数有关,但是当更新参数没有 $each 时它工作正常(即它将整个数组 (A) 推入数组字段)
  • 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我考虑过在下面的解决方案中使用 $addToSet,但正如您在上面的示例代码中所见,我想推送所有对象,即使它们不是唯一的: Mongoose - 将对象推送到嵌套数组中

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

It turns out the IDs did not match.结果发现 ID 不匹配。 There was no issue with the code.代码没有问题。 Sorry guys.对不起大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM