如何在MongoDB中使用put请求将值推送到嵌套数组中?

eqoofvh9  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(120)

如何将"userid"(它是一个字符串)添加到MongoDB中的嵌套数组"people_attending"中?问题是我无法添加到数组people_attending中。
下面是我的MongoDB模式:

const OrganizationSchema = new Schema({
      name: {
        type: String,
        required: true,
        unique: true,
      },
      register_date: {
        type: Date,
        default: Date.now,
      },
      teams: [
        {
          sport: {
            type: String,
            required: false,
          },
          events: [
            {
              date_time: {
                type: Date,
                offset: true,
              },
              opponent: {
                type: String,
                required: true,
              },
              people_attending: [String],
              amenities: [String],
            },
          ],
        },
      ],
    });

下面是我的尝试:

  • 我希望找到等于给定eventid的事件,并将userid添加到people_attending数组中。
router.put("/event/attend/:orgid/:teamid/:eventid/:userid", (req, res) => {
  const userid = req.params.userid;
  const eventid = req.params.eventid;
  const teamid = req.params.teamid;
  const orgid = req.params.orgid;
  console.log(teamid, userid, eventid);
  Organization.findOneAndUpdate(
    { _id: orgid, "teams._id": teamid, "teams.events._id": eventid },
    {
      $addToSet: {
        "teams.$.events.$.people_attending": userid,
      },
    }
  )
    .then((team) => {
      res.status(200).json(team);
    })
    .catch((err) => {
      res.status(400).json(err);
    });
});
pb3s4cty

pb3s4cty1#

找到了解决办法:

Organization.findOneAndUpdate(
    { _id: orgid, "teams._id": teamid, "teams.events._id": eventid },
    {
      $addToSet: {
        "teams.$.events.$[].people_attending": userid,
      },
    },
    { new: true }

相关问题