NodeJS 如何从mongodb中删除多个文档

rn0zuynd  于 2022-11-29  发布在  Node.js
关注(0)|答案(1)|浏览(213)

我试图deleteFeature同时我想删除所有与该功能相关的评论,但我不知道如何做。

我的deleteFeature方法-

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

我有这个评论模型-

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

因此,删除要素时,我希望删除该要素字段中包含该要素的_id的所有注解

djmepvbi

djmepvbi1#

变更

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

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

相关问题