Adding the User ID to Posts in MEAN Stack
In our previous section, we successfully added the creator key to our data schema. Now, we need to add the user id to the posts, so in this section, we will learn how to connect posts with the user id. We will make changes in some post routes for that. We will use the following steps to do that:
1) We will go to our post route, i.e., the posts.js file in the routes folder. We will reach out to that route where we are creating a new post. In this route, we store a title, content and imagepath, and now we need to populate that creator field too. We will add creator property, and for its value, we have a question, i.e., from where we get the user Id. We will fetch the id from the token by decoding the token. We will decode the token to get the information.
Now, if we go back to our middleware, we already verify the token, and the verify method retrieves the token for us. It gives us a decoded token. So, we will store the result in a constant first, and then we can access the data which is inside that token.
Now, every middleware running after this check-auth middleware will get that extra piece of information.
3) If we look at our post.js file, we will see that our middleware where we try to create a new post is running after the check-auth middleware. It means we will have that extra piece of information, i.e., the userData field. So, now, we will pass the value to that creator field we created before in the following way:
Now, we should be able to store the userId as part of our post.
4) Now, we will go back to our posts.service.t file where we are fetching all the posts. We will simply go to our subscribe method and console log our transformedPostData to ensure whether they contain userId or not.
5) One important thing to keep in mind, we were mapping the post data above of the subscribe method. Now, we are mapping it into a new object where we don't use that creator Id anymore. So, we will add that creator Id field here too.
Now, we will save all the files and go back to our angular app. If we add a new post, we will see the creator information attached to the post.
Now, we attach the user id with posts, and our code is also working well. In the next section, we will use the creator id on the backend to deny any delete or update request by another user for a given post.