Removing one-one and one-many references - Mongoose

前端 未结 2 1121
你的背包
你的背包 2020-12-05 11:28

I have an Assignment schema which has references to Groups and Projects.

Assignment == Group [One-One Relationship]
A         


        
2条回答
  •  -上瘾入骨i
    2020-12-05 11:52

    In the remove middleware, you're defining the actions to take when a document of the model for that schema is removed via Model#remove. So:

    • When a group is removed, you want to remove the group reference to that group's _id from all assignment docs.
    • When a project is removed, you want to remove the projects array element references to that project's _id from all assignment docs.

    Which you can implement as:

    GroupSchema.pre('remove', function(next) {
        var group = this;
        group.model('Assignment').update(
            { group: group._id }, 
            { $unset: { group: 1 } }, 
            { multi: true },
            next);
    });
    
    ProjectSchema.pre('remove', function (next) {
        var project = this;
        project.model('Assignment').update(
            { projects: project._id }, 
            { $pull: { projects: project._id } }, 
            { multi: true }, 
            next);
    });
    

提交回复
热议问题