Automatically remove referencing objects on deleti

2019-01-18 02:17发布

问题:

Let's suppose I have a schema like this:

var Person = new Schema({
    name: String
});

var Assignment = new Schema({
    name: String,
    person: ObjectID
});

If I delete a person, there can still be orphaned assignments left that reference a person that does not exist, which creates extraneous clutter in the database.

Is there a simple way to ensure that when a person is deleted, all corresponding references to that person will also be deleted?

回答1:

You can add your own 'remove' Mongoose middleware on the Person schema to remove that person from all other documents that reference it. In your middleware function, this is the Person document that's being removed.

Person.pre('remove', function(next) {
    // Remove all the assignment docs that reference the removed person.
    this.model('Assignment').remove({ person: this._id }, next);
});


回答2:

If by "simple" you mean "built-in", then no. MongoDB is not a relational database after all. You need to implement your own cleaning mechanism.



回答3:

you can use soft delete. Do not delete person from Person Collection instead use isDelete boolean flag to true.