我在 mongoose 中有这 3 个模型:
旅行架构
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
});
旅行和产品具有“一对多”关系,产品和发票具有“一对多”关系。 我需要以下内容: 删除旅行后,与该旅行相关的所有产品也会被删除。
当这些产品被消除时,与每个产品相关的所有发票也被消除。
我已设法消除所有产品,但当我尝试消除发票时,我没有获得产品的 ID。
invoiceSchema.pre('deleteMany', (next) => {
console.log(this);
// this print { n: 2, ok: 1, deletedCount: 2 }
})
我认为在考虑删除所有相关文档时,您应该以其他方式开始。就像你有
travel id
first
删除应该是
invoices
所在的 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
可能会存在一定的性能问题。