Adding a Reference to the Model in MEAN Stack
In our previous module, we successfully added authentication. From this section, we are going to start a new model, i.e., Authorization. Authentication and Authorization both are slightly different things. In our last section, we made sure that the users interacting with our app need to be authenticated, which means they need to have an account in order to be able to create posts, edit posts or delete posts.
Authorization goes one step further. We don't want to allow every user to edit or delete every post. Users should be connected to the posts they created in the database. We need to store the ID of the user who created a post, and then when a user tries to delete a post, we want to check that the user who is trying to delete the post is the user who created this. We will implement the authorization step by step, and in this section, we will first add a reference to the model. We will use the following step to do that:
1) We want to store the information about which user created which post in our database. We could either store a list of posts in our user object, or a list of users or one user to be precise on our posts because each post will only be created by one user. We will go back to our post model, i.e., the post.js file in the "models" folder and edit it. We will add a new field, i.e., creator, and the type of this field will not be a string. It will be a Mongoose ID object because it is going to be an ID. We also require this, so we will set the required to true.
2) We want to add an extra piece of information. We are telling the mongoose that we are going to store an ID, but we want to tell the mongoose to which model this ID will relate. Therefore, we will add an extra property, i.e., ref. The ref property allows us to define to which model this ID we are going to store will belong. That will be our user model because we are going to store a user ID.
This extra piece of information will be added automatically. The user doesn't need to add it into the form where he creates the post. It will be inferred from that token which we pass with a request reaching our backend. To proceed next, we have to delete all the posts from the database first. So, we will delete all the posts from the database.
We successfully added the creator key to our data schema. In the next section, we will use that schema and store that information whenever a new post is created.