0

I have an array in my model document. I would like to remove one id in that array. Is this possible?

document with array of object id's

This is what I tried.

module.exports.RemoveFavourite = async (req, res, next) => {
  try {
    const userId = req.params.user;
    const favouriteId = req.params.event;

    const removeFavourite = await User.updateOne(
      { _id: userId },
      { $pull: { favourites: favouriteId } }
    );

    res.status(200).json(removeFavourite);
  } catch {
    res.status('404').json('error');
  }
};

Harvey
  • 46
  • 5
  • i think same here. [mongoose-delete-array-element-in-document-and-save](https://stackoverflow.com/questions/14763721/mongoose-delete-array-element-in-document-and-save) – BKs0Lk1 Jan 09 '23 at 09:59
  • The query [looks good](https://mongoplayground.net/p/0hjOTiYaRW1) so maybe you have to parse `favouriteId` to `ObjectId`. By the way you can try to do a `find` query to ensure data is ok. If aquery [like this](https://mongoplayground.net/p/MjFv68X3v2y) works properly, the update should too. – J.F. Jan 09 '23 at 10:02

1 Answers1

1

convert favouriteId string to ObjectId

const mongoose = require("mongoose")

module.exports.RemoveFavourite = async (req, res, next) => {
  try {
    const userId = req.params.user;
    const favouriteId = req.params.event;

    const removeFavourite = await User.updateOne(
      { _id: userId },
      { $pull: { favourites: mongoose.Type.ObjectId(favouriteId) } }
    );

    res.status(200).json(removeFavourite);
  } catch {
    res.status('404').json('error');
  }
};
Mandeep
  • 364
  • 2
  • 16