node.js - 在 MongoDB 中删除时自动删除引用对象

标签 node.js mongodb mongoose

假设我有这样的架构:

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

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

如果我删除了一个人,仍然会留下引用不存在的人的孤立分配,这会在数据库中造成多余的困惑。

有没有一种简单的方法可以确保当一个人被删除时,对该人的所有相应引用也将被删除?

最佳答案

您可以添加自己的'remove' Mongoose middlewarePerson 架构上将该人从引用它的所有其他文档中删除。在您的中间件函数中,this 是要删除的 Person 文档。

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

关于node.js - 在 MongoDB 中删除时自动删除引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11904159/

相关文章:

javascript - 使用数组条件更新 mysql 数据库

node.js - 尝试在 Mongoose 中动态生成 _id,但返回对象

Mongodb - 如何在查找查询中使用聚合文本搜索

java - MongoDB Java驱动程序3.2 : parsing Json String to ArrayList<Document>

linux - 群晖NAS服务器上的mongoctl

mongodb - Mongodb聚合$ group,限制数组的长度

javascript - Mongoose : How to remove item from array by value

jquery - 在 Ubuntu 14.04 上通过 npm 安装 jsdom 的问题

node.js - 上传数据时暂停 Node csv-parser

node.js - Nodejs 读写 excel 文件的最佳实践是什么?