Buy real YouTube subscribers. Best price and warranty.
Get Free YouTube Subscribers, Views and Likes

MERN Stack u0026 GraphQL - #13 Models u0026 Relationships

Follow
Code Realm

In this video, we're finally going to work on schema design and figure out the relationships between models, including users, chats, and messages. We'll start by declaring GraphQL types and defining Mongoose models, as well as associating them through ObjectId references.

At the pinnacle of the hierarchy, we have Users who are going to sign up in the app. They will then create Chats (i.e. channels) and invite other users to join in. Once a Chat is created, a User can start sending Messages. In effect, the key entities are User and Message, whereas Chat acts as a bridge to link the two together (as a junction table would do in SQL).

Each User can create many Chats, and each Chat can accommodate many Users, hence the relationship is manytomany. A Chat can have millions of Messages, but each Message only belongs to a single Chat; they are thus related via onetomany. By the same token, each Message is also sent by a particular User, and while Users can send hundreds of Messages, every Message belongs to only one User. So, the relationship there is onetomany as well.

To express the onetomany rel. between Chat and Messages, each Message will carry a chat ID reference pointing back to its parent. I originally contemplated assigning an array of message IDs to Chat, but I gave up on that idea for a few reasons:

it complicates the code unnecessarily, because we'd need to constantly keep the array in sync by $pushing or $pulling message IDs

it is less scalable, because a document in MongoDB can only hold as much as 16 MB of data, so we could theoretically hit a threshold when pushing new IDs will not be feasible

it has performance implications for read operations, as we'd need to index the entire array of IDs to optimize the reads

While it's not likely that our app will rise to the ranks of Facebook or Twitter, it wouldn't hurt to consider scaling. So, let's go with the most optimal design up front and save ourselves from headache down the road.

By default, chats will be private, meaning a member needs to invite an outsider, so they could join in. I believe this is how it works in Slack or Google Hangouts. Eventually, we could work on public channels as well, as I don't think it'd be very hard to implement. Besides, we'll add functionality to edit and delete messages (and chats) as well. But for now, let's give users the ability to initiate a chat and send messages. We'll work on that next.

Refresher on relationships in MongoDB http://learnmongodbthehardway.com/sch...

OnetoMany Relationships with References https://docs.mongodb.com/manual/tutor...

Don't forget to follow up on the repo https://github.com/alex996/graphqlchat

posted by CydayCitambumyy