'MongoDB Delete all documents that created by user when deleting user
I'm working on MongoDB (mongoose) and NodeJS. I have a problem. I'm makine a RESTful API. I have Users model (collection) and Comments model (collection). Users creates comments, and i relate the User and User's Comments with User's _id. l want to delete all comments when user deleted. How can I make this in MongoDB? I search it on Google for 2 days but İ l can't find a good source, looked at MongoDB Manual Documents, but i didn't find anything.
Please help me. Thanks, have a good day...
Solution 1:[1]
If you are using parent referencing
userSchema.post('findOneAndDelete', async id => {
await Comments.deleteMany({ user: id });
});
If you are using child referencing
userSchema.post("findOneAndDelete", async function (user) {
if (user.comments.length) {
const res = await Comment.deleteMany({ _id: { $in: user.comments } });
console.log(res);
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
