在 MongoDB 中删除时自动删除引用对象 [英] Automatically remove referencing objects on deletion in MongoDB
问题描述
假设我有一个这样的架构:
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?
推荐答案
您可以添加自己的 'remove'
Mongoose 中间件 以从引用它的所有其他文档中删除该人.在您的中间件函数中,this
是要删除的 Person
文档.
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);
});
这篇关于在 MongoDB 中删除时自动删除引用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!