如何删除猫鼬nodejs中所有id的引用?

时间:2020-05-28 01:35:35

标签: node.js express mongoose

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
  }

});

在这种情况下,如果我从foodschema中删除食物,如何删除shopchema中引用的foodid

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

};

如果我们删除ID中的任何一个,猫鼬中是否有任何功能可以删除所有参考ID?

2 个答案:

答案 0 :(得分:0)

我不明白您是否尝试删除整个记录只是使用

Shop.deleteMany({foodID:fid})

如果您尝试仅从记录中删除foodID参数,请将其设置为NULL

Shop.updateMany({foodID:fid},{foodID:null})

答案 1 :(得分: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'});
  });

};

我得到了答案,但是如果我们删除ID中的任何一个,猫鼬中是否有任何功能可以删除所有参考ID?