n3pixowe
n3pixowe

Reputation: 122

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...

Upvotes: 1

Views: 1964

Answers (2)

Mohammed
Mohammed

Reputation: 1032

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);
      }
   });

Upvotes: 0

iofjuupasli
iofjuupasli

Reputation: 3873

MongoDB doesn't support built-in relations and transactions among collections.

To remove related Comments (I suppose you have userId field in each Comment):

db.comments.remove({userId: removedUserId})

If you have collection of ids of comments in User, then:

db.comments.remove({id: {$in: collectionOfCommentIds}})

Mongoose does support middlewares. But notice that

There is no query hook for remove(), only for documents.

So you can define remove hook for use with user.remove(). But not for User.remove({_id: userId})

userSchema.post(`remove`, (user) => {
    Comments.remove({userId: user._id})
})

Upvotes: 4

Related Questions