【问题标题】:$push to update nested array in Mongoose and return added object$push 更新 Mongoose 中的嵌套数组并返回添加的对象
【发布时间】:2016-05-21 21:17:32
【问题描述】:

我的 MongoDB 的结构是这样的……

Database (Job Application Database)
   ...
   Nested Array of Objects (Applicants)
      ...
      Another Nested Array of Objects (Comments)

我有这段代码可以正常工作来更新嵌套数组

JobApplication.findOneAndUpdate(
   { _id: new ObjectId(data.job_app_id), 'applicants._id' : new ObjectId(data.selected_applicant_id) },
   {'$push': {'applicants.$.comments': data.message}},
   {safe: true, upsert: true, new : true},
   function(err, model) {
        console.log(err);
        console.log(model);
   }
)

我遇到的问题是它没有返回添加的对象。我不只是返回data.message 的原因是因为我需要对象的_id。有没有办法返回添加的对象?

【问题讨论】:

  • 这里的问题是“upsert”。想一想为什么当您在数组中查找内容时这可能是个问题。这两者不能很好地融合有一个非常合理的原因。
  • @BlakesSeven 请解释一下原因?

标签: arrays node.js mongodb mongoose nested


【解决方案1】:
`JobApplication.findOneAndUpdate(
   { _id: new ObjectId(data.job_app_id), 'applicants._id' : new ObjectId(data.selected_applicant_id) },
   {'$push': {'applicants.$.comments': data.message}},
   {safe: true, upsert: true, new : true},
   function(err, model) {
if(err) return JSON.stringify(err)
        if(model){
console.log(model) }
)`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2017-11-17
    相关资源
    最近更新 更多