mongodb - 如何在带有猫鼬的几个模型中级联删除?
问题描述
我在猫鼬中有这 3 个模型:
TravelSchema
var travelSchema = new mongoose.Schema({
name: String,
description: String,
mexican_currency_value: mongoose.Schema.Types.Decimal128
})
travelSchema.pre('deleteOne', function(next) {
const id = this.getQuery()['_id'];
Product.deleteMany({ travel: id }, (err, value) => {
});
next();
});
产品架构
var productSchema = new mongoose.Schema({
name: String,
description: String,
purchased_amount: Number,
unit_price_mex: mongoose.Schema.Types.Decimal128,
unit_price_to_sell: mongoose.Schema.Types.Decimal128,
travel: { type: mongoose.Schema.Types.ObjectId, ref: 'Travel' }
})
发票架构
var invoiceSchema = new mongoose.Schema({
product: productSchema,
client: { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
purchased_amount: Number,
fch: String
});
其中 Travel 和 Product 具有一对多的关系,而 Product 和 Invoice 具有一对多的关系。我需要以下内容:
删除旅行时,与该旅行相关的所有产品也将被删除。
当这些产品被消除时,与每个产品相关的所有发票也被消除。
我已经设法消除了所有产品,但是当我尝试消除发票时,我没有获得产品的 ID。
invoiceSchema.pre('deleteMany', (next) => {
console.log(this);
// this print { n: 2, ok: 1, deletedCount: 2 }
})
解决方案
我认为您在删除所有相关文档时应该以另一种方式开始。就像您拥有的一样travel id
,使用它获取所有产品并将它们的 id 存储在数组中,然后您的first
删除应该是invoices
where product._id: { $ in: _arrayOfProducIds }
。一旦完成,那么deleteMany
你products
已经有了它们ids
,_arrayOfProducIds
最后处理Travel
:
travelSchema.pre('deleteOne', function(next) {
const id = this.getQuery()['_id']; // travel id check
// Query to get all the product ids based on the travel id and return array for `$in`
const productIds = this.DoYourQuery // [productIds] check
Invoice.deleteMany({'product._id': { $in: productIds }}, // ... etc
Product.deleteMany({ _id': { $in: productIds }}, // ... etc
next();
});
我会假设您没有大量的产品和发票......从那时起$in
可能会有数千个性能问题。希望这可以帮助。
推荐阅读
- php - 从对象创建关联数组
- javascript - 编写一个 JavaScript 条件语句来查找三个数字的乘积的符号。显示带有指定符号的警告框
- xpath - XPath:检查是否需要第一个孩子
- python-3.x - 从 2 张图像重建场景的 3D 点云
- python - 在 Windows 10 anaconda 上安装 apache-airflow 时出错
- java - Java LinkedBlockingQueue:检查元素是否已经存在
- c# - 在 C# 中创建 Microsoft Access 查询
- django - 如何为 django 用户添加禁用密码
- c - 函数 main (Turbo-C) 中的表达式语法
- ios - 将 AVPlayerLayer 添加到 UIViewController