Creating Backend Routes and User Model for Login and Signup in MEAN Stack
Our previous section successfully designed the login and signup page, but we didn't implemented the backend for both of them. So, in this section, we will implement the backend for creating users or logging users in. Below are the steps which we will use to create the backend.
2) We will import our express and create the router in the same way as we have implemented in our js file. After creating the router, we will also export this at the very bottom of the code like as:
3) Now, we will register the routes, and we want to have two routes for now or two post routes to be precise. Our first post route will handle all requests going to api/user/signup.
In our post route, we passed only "/signup," and to make sure that we have api/user in front of this, we will go to the app.js file where we imported our posts routes and implement our user routes like this:
4) We will go to the bottom of our js file where we set up our postsroutes and forward request aiming at /api/posts/something to the post routes. We will do the same for requests targeting api/user/something, and we will forward them to the userRoutes:
So, any requests where the paths start with /api/user will go into our user.js file, and anything which has, then a /signup, after that will reach this route.
5)b In our post route of the user.js file, we will have the well-known function with the request, response and next, where we can handle the incoming requests.
7) In this file, we will import our mongoose and create a new schema for that. We will create a schema name userSchema. In our schema, we will have an email that is of type string and a password, which is also of type string. At the bottom of the code, we will export our mongoose model so that we can use it.
In the above code, we used unique. It does not act as a validator, which means it doesn't automatically throw an error if we try to add a new entry with an email address that does already exists. It will eventually lead to problems, but we cannot rely on this validating data when we try to save it. Unique allows mongoose and mongodb to do some internal optimization from a performance perspective. Unlike required, it is not there to validate input, which would throw an error if we don't provide an email.
8) Now, we want to make sure that we don't save user data or a user with the same user id twice. For that, there is a third-party package, i.e., mongoose-unique-validator, which will add this validation logic for us. We will run the following command to install this package:
9) We will not add it automatically, though; we have to connect it to our schema, which we want to validate. For that, we need to import the mongoose-unique-validator package and then we will use it as a plugin like as:
Our mongoose model is designed for our users, and now we will save our users whenever we get a request sent to our new route here. We will do this in the next section.