gpt4 book ai didi

mongodb - 如何用 Mongoose 在多个模型中级联删除?

转载 作者:可可西里 更新时间:2023-11-01 10:45:05 24 4
gpt4 key购买 nike

我在 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
});

其中 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 在哪里product._id: { $ in: _arrayOfProducIds }。一旦完成,然后 deleteMany 你的 products 因为你已经在 _arrayOfProducIds 中有了他们的 ids 最后处理旅行:

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 可能有点性能问题。希望这会有所帮助。

关于mongodb - 如何用 Mongoose 在多个模型中级联删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com