【问题标题】:Mongoose: Update/Insert in nested subdocumentMongoose:在嵌套子文档中更新/插入
【发布时间】:2018-09-04 15:26:36
【问题描述】:

我在 stackoverflow 中看到了很多示例,但没有一个对我有用。也许我的方案错了?

我需要使用 Mongoose 将新记录插入到嵌套文档中(我想在 "history" 数组中添加)。如果文档已经存在,我必须只更新它,如果它不存在,则必须添加一个新文档。我有以下方案:

let equipment_json = {
    controls: [{
        _id: con.Schema.Types.ObjectId,
        name: String,
        history: [{
            _id: con.Schema.Types.ObjectId,
            new: Boolean,
        }]
    }]
};

let equipment_schema = new con.Schema(equipment_json);
let Equipment = con.mongoose.model('Equipment', Equipment_schema);

此代码应执行更新:

Equipment.update({
  '_id': object_equipment.id_equipment,
  'controls._id': object_equipment.id_control_type
},{
  $set: {
    'controls.$.history.$': {
      new: true
    }
  }
},
{
  upsert: true, setDefaultsOnInsert: true
},
function (err, doc ) {
  console.log( doc );
})

在使用update() 之前,我使用find() 来检查它根据标准找到的内容。使用find(),它会返回文档,但是,当我想使用update() 时,它不会添加到数组“controls""new": "true"。我尝试了$set$push .

【问题讨论】:

  • 您没有说要匹配历史数组的哪个元素。呼叫网站上是否只有一个、多个?
  • 我需要将“new”的值添加到“history”数组中,只要“_id”和“controls._id”匹配即可。

标签: node.js mongodb mongoose


【解决方案1】:

只需要修改以下代码:

'controls.$.history.$': {
   new: true
 }

通过

'controls.$.history': {
      new: true
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2014-06-12
    • 2023-03-10
    • 2016-10-06
    • 1970-01-01
    • 2011-12-21
    • 2020-06-07
    相关资源
    最近更新 更多