---
# System prepended metadata

title: 'Learning JWT Part 3 - Setup controllers, model and signup first user'
tags: [JWT]

---

Learning JWT Part 3 - Setup controllers, model and signup first user
===
![](https://i.imgur.com/qFSfCl5.png)




---
###### tags: `JWT`



### MVC - Controllers

Why do we need a controller? It Contains logic that updates the model and/or view in response to input from the users of the app and the core of receiving request/response.

Before we seperate our callback function from router, it would like code below.

```javascript=
const { Router } = require("express");
const router = Router();

// Create routes here
router.get("/signup", (req, res) => {...});
router.post("/signup", (req, res) => {...});
router.get("/login", (req, res) => {...});
router.post("/login", (req, res) => {...});

module.exports = router;
```

Let's create a folder called **controllers**, inside folder, create a file called **authControllers.js**, migrate callback functions from **authRoutes.js** to here, then we can import them in **authRoutes.js**

```javascript=
// authControllers.js

module.exports.signp_get = (req, res) => {
    res.render("signup");
}

module.exports.login_get = (req, res) => {
    res.render("login");
}

module.exports.signp_get = (req, res) => {
    res.render("signup");
}

module.exports.signup_post = (req, res) => {
    res.render("Create a user");
}

module.exports.login_post = (req, res) => {
    res.render("Login a user");
}
```

Import these controllers.

```javascript=
// authRoutes.js

const { Router } = require("express");
const authController = require("../controllers/authController");
const router = Router();

// Create routes here
// Since we import authController, after typing authController with dot notation, 
// you can see the controllers list out automatically we have defined earlier.

router.get("/signup", authController.signup_get);
router.post("/signup", authController.signup_post);
router.get("/login", authController.login_get);
router.post("/login", authController.login_post);

module.exports = router;
```
![](https://i.imgur.com/W1frCkX.png)

---

### MVC - Model
The model defines what data the app should contain. For example, in this small project, we will need to store user data in MongoDB, so let's create a **User** model.

Here we use [mongoose](https://mongoosejs.com/docs/guide.html) to connect MongoDB.

#### Mongoose core concept
- **Schema**: Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
    - i.e. An **Users** collection in MongoDB.
    - We need to define what kind of information (data) that we want to store in **Users** collection.
    - Below we have created a schema that describe the shape of the documents **(User)** within the collection **(Users)**

```javascript=
// User.js

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  }
});

// Define an user model with this mongoose instance
const User = mongoose.model("user", userSchema);
```

> [Mongoose.prototype.model()](https://mongoosejs.com/docs/api.html#mongoose_Mongoose-model)

---

### Create first user

Here we are going to use **User** schema to simulate signing up.

First of all, we need to change code in **authController.js**

```javascript
const User = require("../models/User");

module.export.signp_post = async (req, res) => {
    // The format would be application/json
    const { email, password } = req.body;
    
    try {
        // Properties passed here must be matched in the User schema
        const user = await User.create({ email, password });
        res.status(201).json(user);
    } catch(error) {
        console.log(error);
        res.status(400).json("Failed to create an user")
    }
}
```

Let's test by using [Postman](https://www.postman.com/). 

- Click **+** to create a new request.
- Select **Post**
- Enter URL: **http://localhost:3000/signup** (Replace port if you'r node is not listening to 3000).
- Select **Body**, **raw** and select **JSON**.

```json
{
    "email": "test@gmail.com",
    "password": "123456"
}
```

Send the request, then you should be able to see the result.

![](https://i.imgur.com/vdCP0tY.png)

Go to MongoDB to check if user data has sent to DB.

![](https://i.imgur.com/c610b46.png)

---
