首页 > 解决方案 > 如何在带有猫鼬的几个模型中级联删除?

问题描述

我在猫鼬中有这 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 }
})

标签: mongodbmongoosemongoose-schema

解决方案


我认为您在删除所有相关文档时应该以另一种方式开始。就像您拥有的一样travel id,使用它获取所有产品并将它们的 id 存储在数组中,然后您的first删除应该是invoiceswhere product._id: { $ in: _arrayOfProducIds }。一旦完成,那么deleteManyproducts已经有了它们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可能会有数千个性能问题。希望这可以帮助。


推荐阅读