如何更新子数组?

How to update sub-array?

我知道如何在 Feathers 中创建东西 (systemService.create(category);),但我如何在子集合中创建东西?

我想将 category 插入 systemService[0].productCategories,但还不知道该怎么做。这是我的服务的屏幕截图。

有人对我应该如何进行有任何建议吗?


编辑:找到了一个几乎有效的解决方案。

systemService.find((error, categories) => {
  const $id = categories[0]._id;

  systemService.update($id, {
    "$set": {
      "productCategories": [
        newCategory
      ]
    }
  });

  console.log(categories);
});

但是,它只是替换 productCategories 中已有的内容,而不是添加内容。我试过 patch,但什么也没发生(所以我可能做错了,或者这不是答案)。

使用 Mongoose 或 Mongodb 时,$push 运算符应该满足您的需求:

systemService.find((error, categories) => {
  const $id = categories[0]._id;

  systemService.update($id, {
    "$push": {
      "productCategories": [
        newCategory
      ]
    }
  });

  console.log(categories);
});