将对象推入对象数组中的猫鼬

时间:2018-12-01 04:49:56

标签: javascript mongodb express mongoose

我正在尝试将对象添加到组件数组中。但是,此components数组位于projects对象内的"scenes"数组中。这是我的折断路线,还有一个项目模型,用于显示模型中所有字段的位置。我似乎无法解决这个问题,并且花了我几个小时才能诊断出问题。

{
    "_id": {
        "$oid": "5c01c26ec028296289f53b00"
    },
    "update": false,
    "publishStatus": "draft",
    "user": {
        "$oid": "5bee30aed343c30016a664b5"
    },
    "projectName": "Griffith Uni",
    "description": "sdaidjasidjasidjiasdjsad",
    "scenes": [
        {
            "_id": {
                "$oid": "5c01c29dc028296289f53b02"
            },
            "sceneName": "Persona Choose",
            "components": []
        },
        {
            "_id": {
                "$oid": "5c01c2acc028296289f53b04"
            },
            "sceneName": "Home Menu",
            "components": []
        },
        {
            "_id": {
                "$oid": "5c0208b16c550072b6b3b499"
            },
            "sceneName": "The Smiths",
            "components": []
        }
    ],
    "lastUpdated": {
        "$date": "2018-11-30T23:06:22.173Z"
    },
    "__v": 0
}

router.post(
  "/projects/scenes/components/new",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const newComp = new Components({
      content: req.body.content
    });
    Project.findById(
      { _id: req.body.projectID },
      Project.findByIdAndUpdate(
        { _id: req.body.sceneID },
        { $push: { components: newComp } },
        () => res.json(newComp)
      )
    );
  }
);

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则可以使用以下代码来实现。

 router.post(
   "/projects/scenes/components/new",
   passport.authenticate("jwt", { session: false }),
   async (req, res) => {
     const newComp = new Components({
       content: req.body.content
     });

     await Project.findOneAndUpdate(
       { _id: req.body.projectID, "scenes._id": req.body.sceneID },
       {
        $push: { "scenes.$.components": newComp }
       }
     );

    res.json(newComp);
  }
);

a similar issue