为什么不删除挂钩与mongoose中的子文档一起使用?

问题描述 投票:1回答:1

当我在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文档时,删除中间件获取主文档和子文档。

但是,当我只是删除一个子文档时,没有删除被调用的钩子。例如:

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个回答
1
投票

从技术上讲,子doc容器永远不会被删除,因此钩子不会被触发。

来自Mongoose文档:

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

Another post with the same issue

如何在主文档未删除子文档时编写运行的中间件?

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

© www.soinside.com 2019 - 2024. All rights reserved.