Mongoose:更新在嵌套数组对象中不起作用

thtygnil  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(170)

我有一个包含对象数组的文档,一个对象包含多个对象,我想用$set更新内部对象,但没有得到任何运气。我该如何解决?
这是我的目标:

{
  "_id": ObjectId("56fbfafdf86fa6161911d104"),
  "site": "xyz",
  "adsPerCategory": NumberInt(2),
  "sampledAt": ISODate("2016-03-30T16:12:45.138+0000"),
  "items": [
    {
      "id": "4563873",
      "content": {
        "title": "WATER DISTILLERS",
        "body": "Perfect to save money.",
      }
    },
    {
      "id": "4563s23232873",
      "content": {
        "title": "Cola water",
        "body": "Perfect for body.",
      }
    }
  ]
}

更新body
现在,我已经给出了single object,但它可以是多个。
这里我尝试了什么

models.Sample.update(
  {
    _id: samples._id
  },
  '$set': {
    'items.0.content.body': body.description
  },
  function(err, numAffected) {
    console.log(err);
    console.log('Affected....', numAffected);
  }
);

如果我把0放进去,它工作得很好,但我想让它成为动态的。
'items.index.content.body': body.description

f87krz0w

f87krz0w1#

我认为你可以做这样的事情。

models.Sample.find({ _id: ObjectId(samples._id) })
   .forEach(function (doc) {
       doc.items.forEach(function (element, index, array) {
          items[index].content.body = body.description;
        });
   models.Sample.save(doc);
 });

相关问题