删除子文档时,如何在Mongoose中删除父文档中的引用?

时间:2018-03-26 05:09:57

标签: mongodb mongoose

在Mongoose中,我有一个父文档,其中包含一系列子引用。

主题有很多主题:

if (window.confirm("Do you really want to ___?")) { 
  // do thing
} else {
  // don't do thing?
}

当我删除某个主题时,我希望从Subject.topics数组中删除它的引用。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

如果您有一个id,也许这样的事情会起作用:

Topics.findByIdAndRemove({ id }, (err) => {
    if(err)
        console.error(err);

    Subjects.update({ 
        "topics" : { $in : [id] } 
    }, { 
        $pullAll : { "topics" : [id] }
    } , (err, subject) => {

    })
})

答案 1 :(得分:0)

我认为你应该使用 mongoose middleware 。 我和你的问题完全相反。如果父文档被删除,那么我也想删除它引用的子文档。我在这里发布我的代码。希望它会对你有所帮助。

我有两个模型文件

  1. RealEstateProperty

  2. RealEstateProject(Parent)

  3. RealEstateProperty:

    var RealEstatePropertySchema   = new Schema({
        Type : { type : String, enum : ['2BHK','3BHK','1BHK','3.5BHK','4BHK','5BHK','1RK','1.5BHK','2.5BHK','4.5BHK','5.5BHK','Penthouse','Plot'], required : true },
        Area : { type : String, required: true },
        Price : { type : Number, required: true },
        NumberOfUnits : { type : Number, required: true },
        Gallery : [{ type : String, required: false }],
        PricePerSquareFoot : { type : Number, required: true },
        CreateDate : { type : Date, required: false },
        UpdateDate : { type : Date, required: false, default: Date.now },
        Project : { type : mongoose.Schema.Types.ObjectId, ref:'RealEstateProject', required : true},
        Status : { type : String, enum : ['Under Construction', 'Ready to move'],required  : false }
    });
    

    RealEstateProject(Parent):

    var RealEstateProjectSchema   = new Schema({
        Name : { type : String, required: true },
        Description : { type : String, required: true },
        DetailAddress : { type : String, required: true },
        ShortAddress : { type : String, required: true },
        Area : { type : Number, required: true },
        City : { type : String, required: true },
        Pincode : { type : Number, required: true },
        CreateDate : { type : Date, required: false },
        UpdateDate : { type : Date, required: false, default : Date.now() },
        IsActive : { type : Boolean, required: false },
        Amenities: [{ type : String, required : true }],
        Possession: { type : String, required : true },
        ProjectType: { type : String, enum : ['Apartment', 'Land', 'Bungalow', 'Row House', 'Villas'], required : true },
    });
    
    //mongoose middleware to remove reference docs
    RealEstateProjectSchema.pre('remove',function(next){
        console.log("Removing property of project " + this._id);
        //code to remove RealEstateProperties reference by RealEstateProject
        //Note : Here you can use $unset to clear the refernce
        this.model('RealEstateProperty').find({ Project : this._id }, function(err,properties){
            if(err){
                console.log("No property found in this project");
            }else if(properties.length == 0){
                console.log("No property found in this project");
            }else{
                for (var i=0; i<properties.length; i++){
                     properties[i].remove(function(delete_err,delete_data){
                        if(delete_err){
                            console.log("No property found in this project");
                        }else{
                            console.log("Properties deleted");
                        }
                    });
                }
            }
        });
        next();
    });
    

    删除RealEstateProject时

    RealEstateProject.findOne({ id : req.body.id })
    .exec(function(err,project){
       if(err){
           console.log(err);
           res.json(err);
       } else{
           if(!project){
               console.log("Project not found");
               res.json({error:"Project not found, invalid Project id"});
           }else{
               project.remove(function(delete_project_err,delete_project_data){
                   if(delete_project_err){
                       console.log(delete_project_err);
                       res.json(delete_project_err);
                   }else{
                       console.log("Project removed successfully");
                        res.json({result:1});
                   }
               });
           }
       }
    });
    

    在“删除”中,调用中间件并使用相同的引用ID删除RealEstateProperty中的文档。