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

2
  • i think same here. mongoose-delete-array-element-in-document-and-save Commented Jan 9, 2023 at 9:59
  • The query looks good 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 works properly, the update should too. Commented Jan 9, 2023 at 10:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.