0

shopSchema

const shopSchema = new Schema({
  shopName: {
    type: String,
    required: true
  },
  foodId: [{
    type: Schema.Types.ObjectId,
    ref: 'Food',
  }]
});

foodSchema

const foodSchema = new Schema({
  foodName: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true
  },
  price: {
    type: String,
    required: true
  },
  shopName: {
    type: String,
    required: true
  },
  shopId:{
    type: Schema.Types.ObjectId,
    ref: 'Shop',
    required: true
  }

});

In this if i delete the food from foodschema how to delete the foodid referenced in shopschema

    exports.postdelfood=(req,res,next)=>{
  const fid=req.params.foodId;
  console.log(fid);
  return Food.deleteOne({_id:fid})
  .then(result=>{
    console.log('deleted');
    res.status(200).json({message:'success'});
  })
  .catch(err=>{
    res.status(500).json({message:'failed'});
  })

};

is there any function in mongoose to delete all the reference id if we delete anyone of the id?

Dharani Shankar
  • 171
  • 1
  • 14
  • Does this answer your question? [Cascade style delete in Mongoose](https://stackoverflow.com/questions/14348516/cascade-style-delete-in-mongoose) – Matheus Hernandes May 28 '20 at 02:22

2 Answers2

0

i don't understand if your a trying to delete the whole record just use

Shop.deleteMany({foodID:fid})

if you are trying to just delete the foodID param from the record just set it to NULL with

Shop.updateMany({foodID:fid},{foodID:null})
Ahmed Magdy
  • 1,054
  • 11
  • 16
  • in shopSchema there is a array of foodId. How to delete the particular food id from shopSchema.foodId. I have already tried your answer, it's not working, Thank you for the early response – Dharani Shankar May 29 '20 at 10:05
0
exports.postdelfood=(req,res,next)=>{
  const fid=req.params.foodId;
  const sid=req.params.shopId;

  return Food.deleteOne({_id:fid})
  .then(result=>{
    console.log(fid);
    Shop.update({_id:sid},{ $pull: { foodId: fid }})
    .then(resu=>{
      console.log(resu);
        console.log('deleted');
      res.status(200).json({message:'success'});

      });    
  })
  .catch(err=>{
    res.status(500).json({message:'failed'});
  });

};

I got the answer but is there any any function in mongoose to delete all the reference id if we delete anyone of the id?

Dharani Shankar
  • 171
  • 1
  • 14