1

I am trying to delete a 'category' document and it's ObjectId that is in an array inside the 'menu' Schema. The 'menu' Schema looks like this :

categories: [
  {
    type: ObjectId,
    ref: "Category",
  },

it holds the ObjectId i am trying to delete

This is the nodejs code from the controller I try to run :

    const deletedCat = await Category.findByIdAndRemove(catId, function (err) {
  if (err) console.error(err)
})
const updateMenu = await Menu.findOneAndUpdate(
  { _id: menuId },
  { $pull: { categories: { _id: new ObjectId(catId) } } },
  { new: true }
)

the $pull doesn't change the DB and the ObjectId is still in the Array.

I also tried without the " new ObjectId "

What am I doing wrong ?

1 Answer 1

3

Ok, so i just got it to work. The answer is simple, just use the ObjectId as a value of the key in the Array (name of the array)

const updateMenu = await Menu.findOneAndUpdate(
  { _id: menuId },
  { $pull: { categories: ObjectId(catId) } },
  { new: true }
)
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, I wondering if you had any issues with this later down the line. I'm getting ObjectId is not defined. Possibly something changed with Mongoose since 2020? I noticed that your model defines the field slightly different, as the docs I've seen show to defined the field as: fieldArray: [{ type: Schema.Types.ObjectId, ref: 'OtherModel'}]. Even when adjusting for that I get schema is not defined. Was there a step you had to do to define ObjectId in the controller making the delete?

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.