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
Asked
Active
Viewed 171 times
1 Answers
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