在我的删除路由中,我调用 Product.findByIdAndRemove(id)
,这将触发 productScheme.pre('remove')
Hook 。我的代码工作正常,只是 console.log
实际上从未在我的终端上输出任何内容,而且我知道它可以工作,因为 Product 文档已从 Categories.products 数组中删除。
我的产品架构
const productSchema = new Schema({
brandName: { type: String, required : true }, // e.g. Holden
name: { type: String, required : true }, // e.g. Commodore
categories: [{ type: Schema.ObjectId, ref: 'Category', default: [] }]
})
productSchema.pre('remove', next => {
console.log('PRODUCT PRE REMOVE') // <--- Never gets outputted. Why?
// The update works
Category.update(
{ products : { $in : this._id } },
{ $pull: { products: this._id } },
{ multi: true })
.exec()
next()
})
我的类别架构
const categorySchema = new Schema({
name: { type: String, unique: true, required : true }, // e.g. Cars
products: [{ type: Schema.ObjectId, ref: 'Product', default: [] }]
})
希望能深入了解为什么会发生这种情况。谢谢!
最佳答案
想通了。对不起大家。
productScheme.pre('remove')
从未真正被触发。
另一方面,当我调用 Product.findByIdAndRemove(id)
时,我的 Category 模型中的产品会自动更新,因为引用设置为 null
并且这会从 Category.products 列表中删除已删除的产品。
类似的行为发生在非列表引用上。如果我的产品架构中只有单个产品(而不是产品列表)的单个类别,则删除该类别时该值将设置为 null
。
关于node.js - Mongoose 预删除有效,但不输出 Console.log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47841471/