Intro to data association

During the weekend I made to the section data association in the tutorials. This part of the section explain what data association is and how we use it. Data association allows us to have multiple collections in our database that are related to one another. There are three different types of data associations; one to one, one to many, and many to many. There are two ways to write these association, by using embedding data and referencing data.

Embedding Data

For embedding data we made two different mongoose schemas, one for users and the other one for posts. In the Post schema we just added the title and the content the user would write. For the User schema we used email, name, and then we create an array where the posts the user writes would be inserted. We used the push method to embed the post created into the user collection. Now the post collection would hold all post created by all users. But the user collection would hold all users and within in each user object it would hold only the posts created by the one user.

Referencing Data

The second way we can create data association is through referencing data. In embedding data we push the whole post into the array but when referencing data we just keep just the ids of the post instead of the whole thing. I first created a new user in the database. When I had to create the post I had to find the user and then push the data from the post into the user object. once the post was created the id of the post would be referenced inside an th array in the user object. Then by using mongoose populate I was able to find the user by id and then targeting the post. When this happens the function runs after where if there isn’t an error it’ll write out the user object with the entire post they have created. But in the database when you search for the user and look in posts only the ids of the posts will come up.

database:

Running the code:

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

css.php