1

When I have a schema in mongoose with nested schemas inside like this

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

const Main = Schema({
  foo: String,
  bar: [Sub],
})
Main.pre('remove', function(next) { ... next() })

When I remove a Main document, the remove-middleware get's called for both the Main and the Sub documents.

But when I just remove a subdocument, no remove-hook get's called. For Example:

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

Is this how it's supposed to be? And if so - how can I write a middleware that runs whenever a subdocument is removed while the main document is not?

Chris
  • 2,069
  • 3
  • 22
  • 27

1 Answers1

1

Well technically the sub doc container is never removed, so the hook will not be fired.

From Mongoose docs:

Each subdocument has it's own remove method. For an array subdocument, this is equivalent to calling .pull() on the subdocument. For a single nested subdocument, remove() is equivalent to setting the subdocument to null.

Another post with the same issue

how can I write a middleware that runs whenever a subdocument is removed while the main document is not?

A possible work around would be to avoid sub docs altogether and create separate models that are related by a unique key.

thomann061
  • 629
  • 3
  • 11