【问题标题】:Why don't remove-hooks work with subdocuments in mongoose?为什么 remove-hooks 不能与 mongoose 中的子文档一起使用?
【发布时间】:2018-08-11 00:51:33
【问题描述】:

当我在 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 文档时,主文档和子文档都会调用 remove-middleware 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

这是应该的吗?如果是这样 - 我如何编写一个在删除子文档而主文档不删除时运行的中间件?

【问题讨论】:

    标签: mongoose mongoose-schema


    【解决方案1】:

    从技术上讲,子文档容器永远不会被删除,所以钩子不会被触发。

    来自Mongoose docs:

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

    Another post with the same issue

    我怎样才能编写一个中间件,当一个子文档被删除而主文档没有被删除时运行?

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

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多