最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Mongoose pre remove有效,但不输出Console.log

运维笔记admin13浏览0评论

Mongoose pre remove有效,但不输出Console.log

Mongoose pre remove有效,但不输出Console.log

在我的删除路线中,我正在调用Product.findByIdAndRemove(id),它将触发productScheme.pre('remove')钩子。我的代码工作正常,除了console.log实际上从未在我的终端上输出任何东西,我知道它的工作原理是因为Product.products数组中删除了Product文档。

我的产品架构

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)时,我的Categories模型中的产品会自动更新,因为引用设置为null,这会从Category.products列表中删除已删除的产品。

在非列表引用上发生类似的行为。如果我的产品架构中只有一个产品(不是产品列表)的单一类别,则在删除类别时,该值将设置为null

发布评论

评论列表(0)

  1. 暂无评论