为什么不';t在mongoose中移除钩子处理子文档?

为什么不';t在mongoose中移除钩子处理子文档?,mongoose,mongoose-schema,Mongoose,Mongoose Schema,当我在mongoose中有一个模式,里面有嵌套的模式,就像这样 const Sub = Schema({ foobar: String, }) Sub.pre('remove', function(next) { ... next() }) const Main = Schema({ foo: String, bar: [Sub], }) Main.pre('remove', function(next) { ... next() }) 当我删除Main文档时,将为主文档和子文档

当我在mongoose中有一个模式,里面有嵌套的模式,就像这样

const Sub = Schema({
  foobar: String,
})
Sub.pre('remove', function(next) { ... next() })

const Main = Schema({
  foo: String,
  bar: [Sub],
})
Main.pre('remove', function(next) { ... next() })
当我删除
Main
文档时,将为主文档和子文档调用删除中间件get

但当我只是删除一个子文档时,不会调用remove-hook-get。例如:

const main = await new Main({
  foo: 'test',
  bar: [{
    foobar: 'test'
  }),
}).save()

await main.bar[0].remove() // or bar.pull()

// pre/post remove hooks on Subdocument not called

应该是这样的吗?如果是这样的话,我如何编写一个中间件,在主文档未被移除时,每当子文档被移除时,它都会运行?

从技术上讲,子文档容器永远不会被移除,因此钩子不会被触发

从文档:

每个子文档都有自己的删除方法。对于数组子文档,这相当于对子文档调用.pull()。对于单个嵌套子文档,remove()相当于将子文档设置为null

我如何编写一个中间件,在删除子文档而主文档未删除时运行该中间件

一种可能的解决方法是完全避免子文档,并创建由唯一键关联的单独模型