0

For years I have worked with relational databases within a LAMP stack, I am now trying to move to a MERN stack and as a result trying to get my head around mongodb and it's flat(?) design.

Previously if I wanted a user to be able to store images I would have had 1:n relationship with the table rows looking similar to this,

user

0001 test1@user.com 2018-05-05
0002 test2@user.com 2018-05-05
0003 test3@user.com 2018-05-05

images

001 filename1.jpg 0001
002 filename2.jpg 0001
003 filename3.jpg 0001
004 filename4.jpg 0002
005 filename5.jpg 0002
006 filename6.jpg 0003

With the last number in the images table being the user_id. Now I have read about mongodb but still follow how I would replicate this, would I embed an images collection within my user collection, like a nested object,or would I have an images collection that somehow references the users id?

Udders
  • 6,914
  • 24
  • 102
  • 194

1 Answers1

-1

I would say: it depends.

If your Image entities aren't shared with other tables and are not accessible standalone (without accessing user), you can keep them in the User collection as an array field.

But if you expect that the Images collection will be shared with other collections, or there's relationship *-to-many between users and images collection, it's better to consider using references (https://docs.mongodb.com/manual/reference/database-references/).

Also if you expect that the images collection will be big (more than few items) it's better to take references as a solution - basically because it's easier for searching.

Vicctor
  • 803
  • 6
  • 13
  • `DBRef` is not supported in any newer MongoDB features. Particularly the main one which actually allows a "server join" of which `DBRef` is not. – Neil Lunn May 16 '18 at 21:41
  • What would an appropriate solution be? – Udders May 16 '18 at 21:51
  • @Udders There are long standing answers here which you have already been pointed at in the links above your question. Consider the pros and cons of whether to embed of reference and it's not a simple case. If you have referenced data then `$lookup` is what you want and it does not and will not support `DBRef`. People who use MongoDB will know this, hence why it is simply not used and not advised by anyone. – Neil Lunn May 16 '18 at 21:57