Home > Mobile >  Node express check mongo object id exists in array if not exist then update
Node express check mongo object id exists in array if not exist then update

Time:11-03

I have a list of array in mongo what I need to do is push Id in list of array and check that if Id exist then it will not push

Right now I push like this

const eventUserGoing = async (req, res) => {
  try {
    const updateuserGoinginEvent = await Events.findByIdAndUpdate(
      req.body.eventid,
      {
        $push: {
          userGoing: req.user.user_id,
        },
      },
      {
        new: true,
      }
    );
    res
      .status(200)
      .json({
        success: true,
        message: 'Event saved successfully',
        data: updateuserGoinginEvent,
      });
  } catch (err) {}
};

I think if its possible by aggregate but don't get what's best what to do this.

CodePudding user response:

Try to use findOneAndUpdate if the event with _id does not already contain the user.
If that is the case, $push the new user:

const eventUserGoing = async (req, res) => {
  try {
    const updateuserGoinginEvent = await Events.findOneAndUpdate(
      { _id: req.body.eventid, userGoing: { $ne: req.user.user_id } },
      {
        $push: {
          userGoing: req.user.user_id,
        },
      },
      {
        new: true,
      }
    );

    res.status(200).json({
      success: true,
      message: 'Event saved successfully',
      data: updateuserGoinginEvent,
    });
  } catch (err) {}
};
  • Related