Thiago Yoithi
Thiago Yoithi

Reputation: 505

MongoDB - How to make this relation?

I have following collections:

clients addresses

Now suppose, I want to be able to add multiple addresses to one client and addresses collection are stored with only addresses names. So all the other information like address reference or street number should be stores on clients embedded data.

I was thinking in something like this:

clients collection's document example:

addresses collection's document example:

Everything looks fine (correct me if I'm wrong, if there is something bad in this approach and if I need to change something). But right now, I'm creating a filter (Angular2 and mongoose as ODM), with clients sorting, is there a way to sort my clients by address name? Considering that I have a default address property? If not, how about if I change something in these collection models? I was thinking to add the address name to the object inside addresses array (client collection) too, so I could sort by something like this: sort(client.address.name)...

One more point is: I separated my addresses in a new collection, because I'll give the user the possibility to import an address database, so I need to have a list of addresses with no clients attached to it.

Upvotes: 1

Views: 67

Answers (1)

satish chennupati
satish chennupati

Reputation: 2650

though there is nothing wrong the way you want to model your collections, but if you follow the MongoDB's documentation https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/

it recommended that its easy to embed documents to maintain one - to - many relations.

how many addresses do you think a client can be associated with ? Go through the link i pasted above is just few lines and it fairly straight forward with good example there. see if that can help you address your query.

Upvotes: 1

Related Questions