Search code examples
javascriptarraysmongodbnestedput

How can I push a value to a nested array by using a put request in MongoDB?


How can I add the "userid" (its a string) to the nested array "people_attending" in MongoDB ? The problem is that I can not add to the array people_attending.

Here is my MongoDB schema:

    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],
            },
          ],
        },
      ],
    });

Here is my attempt:

  • I would like to find the event that equals to the given eventid and add the userid to the people_attending array.

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);
    });
});


Solution

  • Found the solution:

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