【发布时间】:2021-03-01 10:23:19
【问题描述】:
请发现很难删除用户并自动删除用户帖子。我只能单独删除用户或用户帖子,但我希望这样当我从数据库中删除用户时,用户帖子也会被删除
【问题讨论】:
-
这能回答你的问题吗? Cascade style delete in Mongoose
请发现很难删除用户并自动删除用户帖子。我只能单独删除用户或用户帖子,但我希望这样当我从数据库中删除用户时,用户帖子也会被删除
【问题讨论】:
您可以查看 mongoose pre middleware,这样应该可以:
UserSchema.pre('remove', function (next) {
let id = this._id
Post.deleteMany({ user: id }, function (err, result) {
if (err) {
next(err)
} else {
next()
}
})
})
像这样调用中间件:
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')
}
})
}
})
【讨论】: