0

I am trying to deleteFeature meanwhile i want all the comments related to that feature deleted but i don't know how to do it.

my deleteFeature method -

exports.deleteFeature = (req, res) => {   
  try {
    const { slug } = req.params;
    Feature.findOne({ slug: slug.toLowerCase() }).exec((err, feature) => {
      if (err) {
        return res.status(400).json({
          error: errorHandler(err),
        });
      }
      console.log("Test");
      Comment.deleteMany({ _id: feature._id });
      console.log("chest");
 
      feature.remove();
      console.log("Best");
 
      return res.json({
        message: "Your Feature has been Deleted Successfully",
      });
    });
    
  } catch (error) {
    return res.status(400).json({
      error: error,
    });   
  } 
};

I have this on comment model -


feature: {
    type: ObjectId,
    ref: "Feature",
    required: true,
  },

So when i delete a feature, i want to delete all the comments containing that feature's _id on that feature field

Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • Is [cascade style delete in Mongoose](https://stackoverflow.com/questions/14348516/cascade-style-delete-in-mongoose) what you're looking for? – user20042973 Nov 28 '22 at 17:46
  • 1
    Field `_id` the the (unique) primary key of a collection. Thus `{ _id: feature._id }` will never resolve to more than one document. – Wernfried Domscheit Nov 28 '22 at 18:12

1 Answers1

0

Change

 Comment.deleteMany({ _id: feature._id });

to

 Comment.deleteMany({ feature: feature._id });
Martinez
  • 1,109
  • 1
  • 4
  • 13