Modeling DB for uploads on posts and comments

In my app, I have a 1-Many relationship between posts and comments. I have a Posts collection and a Comments collection. In the Comments collection, I reference the postId.

Now, my goal is to allow file uploads on both posts and comments. I plan to have a new Uploads collection. What’s the best way to model this?

Initially, I was thinking of having a contentId field on an Upload document that would store either the post._id or the comment._id as a reference. This seemed like it would work well but then I thought there might be a small chance those ids are the same since, from what I understand, collection ids aren’t necessarily unique across collections.

As an alternative, I was thinking the Posts and Comments collections could have an uploads field that will contain an array of uploadIds. I think this works, but I’m wondering if there’s a better way.

Appreciate any insight you might have.

I would go with this approach.
It makes sense in relational sense (posts and comments have attachments, attachments don’t have posts or comments)
and in a non-relational sense (when rendering a comment, you want to know what attachments to display, so uploadIds should be on comment)

1 Like