在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'
猫鼬中间件在Person
模式上将其从引用该人的所有其他文档中删除.在您的中间件功能中,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屋!