I have a User
model and Post
, Comment
model where Post.author
and Comment.author
reference User._id
...
How can I add a middleware to delete all posts and comments when a user is deleted...
I have seen other questions on stackoverflow with answers involving schema.pre("remove"...
, but now .remove()
has been deprecated...
My desired implementation:
UserSchema = new mongoose.Schema({
...
})
PostSchema = new mongoose.Schema({
author: String // User._id
...
})
CommentSchema = new mongoose.Schema({
author: String // User._id
post: String // Post._id
...
})
UserSchema.post("findOneAndDelete", async (doc) => {
await Post.deleteMany({ author: doc._id });
await Comment.deleteMany({ author: doc._id });
})
PostSchema.post("deleteMany", async (doc) => {
await Comment.deleteMany({ post: doc._id })
})
How can I achieve this in mongoose v7.2.2?