-1

Please am finding it difficult to delete user and also get the user posts removed automatically. I can only delete user or the user posts separately but I want it in a way that when I delete the user from the database the user posts also get deleted

Gabriel
  • 35
  • 1
  • 8
  • Does this answer your question? [Cascade style delete in Mongoose](https://stackoverflow.com/questions/14348516/cascade-style-delete-in-mongoose) – Matt Feb 28 '21 at 21:59

1 Answers1

0

You can look into mongoose pre middleware something like this should work:

UserSchema.pre('remove', function (next) {
  let id = this._id
  Post.deleteMany({ user: id }, function (err, result) {
    if (err) {
      next(err)
    } else {
      next()
    }
  })
})

The call the middleware like this :

User.findById(id, function (err, doc) {
      if (err) {
        console.log(err)
        return res.status(500).send('Something went wrong')
      } else {
        if (!doc)
          return res.status(404).send('User with the given id not found')
        doc.remove(function (err, postData) {
          if (err) {
            throw err
          } else {
            return res.send('User successfully deleted')
          }
        })
      }
    })
O'Dane Brissett
  • 1,284
  • 1
  • 8
  • 23