如何在几种带有猫鼬的模型中级联删除?

时间:2019-06-20 14:51:20

标签: mongodb mongoose mongoose-schema

我的猫鼬有这三种模型:

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();    
});

ProductSchema

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' }
})

InvoiceSchema

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 }
})

1 个答案:

答案 0 :(得分:0)

我认为您在删除所有相关文档时应该以另一种方式开始。就像您拥有travel id一样,它可以获取所有产品并将其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可能不成千上万,这可能是性能问题。希望这会有所帮助。