How to Create User Routes in Node.js: A Step-by-Step Guide
Tags: node, javascript, beginners, tutorial
Published: 2023-11-04 15:25:21

## Table of Contents
- [Introduction](#intro)
- [Create user model](#user-model)
- [Add user to todo model](#todo-model)
- [Create user controller](#user-controller)
- [Create user routes](#user-route)

> *For this series, I'm following an excellent video tutorial from [Traversy Media](https://www.youtube.com/playlist?list=PLillGF-RfqbbQeVSccR9PGKHzPJSWqcsm)*

### Introduction <a name="intro"></a>
In this tutorial, we'll walk you through the process of creating a user model for a Todos application using the Mongoose library. The user model will serve as the foundation for managing user-related data, such as registration, authentication, and user-specific tasks.

### Create user model <a name="user-model"></a>
To begin, we'll create a user model by defining a schema for the user data. This schema will include fields for the user's `name`, `email`, and `password`. Notably, we'll set the email field as unique to ensure the integrity of user data.
```javascript
const mongoose = require('mongoose');

const userSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, 'Please add a name'],
    },
    email: {
      type: String,
      required: [true, 'Please add an email'],
      unique: true,
    },
    password: {
      type: String,
      required: [true, 'Please add a password'],
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model('User', userSchema);
```
By setting timestamps to true, Mongoose will automatically create a `createdAt` and `updatedAt` fields in user collection.

### Add user to todo model <a name="todo-model"></a>
Next, we'll establish a connection between the user and todo models by adding a `user` field to the `todoModel.js`.
```javascript
    user: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'User',
    },
```
Here I'm specifying the user field with `ObjectId` and referencing it to the `User` model.

### Create user controller <a name="user-controller"></a>
Now, I am creating a `userController.js` file in the `controllers` folder and adding a function for registering a user, authenticating/logging a user, and getting the logged-in user data.
```javascript
const registerUser = (req, res) => {
  res.json({ message: "Register User" });
};

const loginUser = (req, res) => {
  res.json({ message: "Login User" });
};

const getLoggedInUser = (req, res) => {
  res.json({ message: "Logged In User data" });
};

module.exports = {
  registerUser,
  loginUser,
  getLoggedInUser,
};
```
Currently, I am just displaying a message. We'll later add the actual functionality to it.
 
### Create user routes <a name="user-route"></a>
To expose these controller functions through API endpoints, we'll create a `userRoutes.js` file and define routes for user registration, login, and retrieval of user data. 
```javascript
const express = require("express");
const router = express.Router();
const {
  registerUser,
  loginUser,
  getLoggedInUser,
} = require("../controllers/userController");

router.post("/", registerUser);
router.post("/login", loginUser);
router.get("/me", getLoggedInUser);

module.exports = router;
```

 and add it to the `server.js` file.
```javascript
...
app.use('/api/goals', require('./routes/goalRoutes'));
app.use('/api/users', require('./routes/userRoutes')); //added user route
...
```
Now run the server go to the postman and check your routes. It will give a result like this.

- Register User

![Register User](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mm0tnmkh3y7l22prauqp.png)

- Login User

![Login User](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2o6958zkajce0hcbtfj6.png)

- Get LoggedIn User

![Logged in user data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3cd219570mb580e8134.png)

Connect with me
- [LinkedIn](https://www.linkedin.com/in/aneeqa-khan-990459135/)
- [GitHub](https://github.com/AneeqaKhan)