Node.js from Beginners to Advance: Part - 2
Tags: node, javascript, webdev, mern
Published: 2021-10-16 10:18:20

## REST API using node, express and MongoDB

This is the second part of the node series; if you're unfamiliar with node, don't worry; we covered everything in the first series, which you can find it here => [dev.to/pramit_marattha/node-js-from-beginners-to-advance](https://dev.to/pramit_marattha/node-js-from-beginners-to-advance-31id)

So, without further ado, let's get this party started.

## So, what exactly is MongoDB?

MongoDB is a cross-platform document-oriented database application that is open source. MongoDB is a NoSQL database application that works with JSON-like documents and optional schemas. MongoDB is a database that was created by MongoDB Inc. and is distributed under the Server Side Public License.

### Now, Let's get this project started right away.

Getting started on our project

Create a new folder and name it whatever you like, then open it in Visual Studio Code and run the code below from the command prompt.

```bash
npm init -y 
```

**Configuring package.json**

To install the dependencies, use the following instructions in the terminal.

```bash
npm i dotenv cors mongoose express nodemon
```
![npm packages](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/letgtc5c6s5rb93vzbpb.png)

 
- dotenv: It is needed to retrieve data from.env files.

- express: node.js web application framework.

- mongoose:  It is a Node. js based Object Data Modeling (ODM) library for MongoDB

- nodemon: It will keep the server running indefinitely.

- cors: It allows cross-origin API requests.

The "package.json" file should look like this after the dependencies have been installed.

```json
{
   "name":"rest",
   "version":"1.0.0",
   "description":"",
   "main":"index.js",
   "scripts":{
      "start":"nodemon server.js"
   },
   "keywords":[],
   "author":"",
   "license":"ISC",
   "dependencies":{
      "cors":"^2.8.5",
      "dotenv":"^10.0.0",
      "express":"^4.17.1",
      "mongoose":"^6.0.8",
      "nodemon":"^2.0.13"
   }
}
```
![dependencies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9bbclcno2ehvrg9fs2b2.png)

And also, remember to update the scripts as well.

![scripts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ov2r5lflfxup2669kf1j.png)

## Structuring the folder:

- **controllers:** The files in the controllers’ folder will contain the methods for the endpoints to interface with the database.

- **models:** The files that specify the MongoDB schema will be found in the model’s folder.

- **dbConfig:** Make a file called db.js in the config folder. The necessary code for connecting to the MongoDB database will be contained in this file.

- **routers:** The files with the endpoints will be found in the routers folder.

![folder structure](https://aviyel.com/assets/uploads/files/1633608733731-image.png)
 
## Configuring server.js

1. Import express and use express() to start our app.

2. Using the app, create a get method for the endpoint http://localhost:6000.

3. For our server to run, set the PORT to 6000.

4. Using our app, you may listen to PORT.

```javascript
//app.js

const express = require("express");
const cors = require("cors");

const dotenv = require("dotenv");

dotenv.config();

const app = express();

const PORT = process.env.PORT || 5000;

// listen
app.listen(PORT, () =>
	console.log(`Server is running on http://localhost:${PORT}`)
);

```
Now use the following code to start the server with nodemon. Ensure that the following command is executed from the project directory.

```bash
npm start
```
If the server has started successfully, the terminal should display the following message.

![npm start](https://aviyel.com/assets/uploads/files/1633672375118-output-resized.jpg)

## Getting started with MongoDB

![Mongodb meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qn1ugj8dej5ww85ob96.png)

- Sign in to MongoDB

- Make a new project.
 
![make new project](https://aviyel.com/assets/uploads/files/1633609044884-image.png)
 
- Create a cluster

![cluster](https://aviyel.com/assets/uploads/files/1633609157284-image-resized.png)

![cluster creation](https://aviyel.com/assets/uploads/files/1633609192655-image-resized.png)

- Choose a cloud service provider.

![cloud service](https://aviyel.com/assets/uploads/files/1633609274997-image.png)

- Make a cluster

- Wait for the cluster to be built before proceeding (usually takes around 5 -10 minutes)

![wait for cluster](https://aviyel.com/assets/uploads/files/1633609341646-image-resized.png)

- Allow access from anywhere by clicking connect. Then IP address should be added.

![add ip address](https://aviyel.com/assets/uploads/files/1633609405584-image.png)

![connect a cluster](https://aviyel.com/assets/uploads/files/1633609429296-image.png)

- Create a user in the database. For the MongoDB URI, you'll need the username and password.

- Select a connection method by clicking on it.

- Connect your application by clicking on it.

- Choose the appropriate driver and version.

- Copy and paste mongodb+srv into the.env file.

```env
PORT=6000
MONGO_DB_URL=mongodb+srv://admin:-----------@cluster0.2qee0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
```

Now open the database.js file in the dbConfig folder and make the modifications listed below.

- Import Mongoose.

- MONGO_DB_URL should be imported from the.env file.

- Define the configDatabase method for establishing a database connection.

- The configDatabase method should be exported and called in server.js.

```javascript
//database.js

const mongoose = require("mongoose");
require("dotenv").config();

const dbURL = process.env.MONGO_DB_URL;

const configDatabase = async () => {
  try {
    await mongoose.connect(dbURL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log("Database connected");
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
};

module.exports = configDatabase;

```
Add the following changes on server.js file

```javascript
// server.js

const express = require("express");
const cors = require("cors");
const configDatabase = require("./dbConfig/database.js");

const dotenv = require("dotenv");

dotenv.config();

const app = express();

const PORT = process.env.PORT || 5000;

//connecting to the mongodb database
configDatabase();

app.use(cors({ origin: true, credentials: true }));

// add the middlewares
app.use(express.json({ extended: false }));
app.get("/", (req, res) =>
  res.send("Hello there!! Cheers !! The server is up and running")
);

// listen
app.listen(PORT, () =>
  console.log(`Server is running on http://localhost:${PORT}`)

```

## Defining database schema:

Add a todo.models.js file inside the models folder. We will define the entire db schema inside this particular file.

```javascript
// todo.models.js

const mongoose = require("mongoose");

const TodoListSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

const Todo = mongoose.model("todo", TodoListSchema);

module.exports = Todo;

```

## Defining the entire endpoint of our API

```javascript
// todo.routes.js

const express = require("express");

const router = express.Router();

const {
  listAllTodo,
  createTodo,
  updateTodo,
  deleteTodo,
} = require("../controllers/todo.controller.js");

router.get("/", listAllTodo);

router.post("/", createTodo);

router.put("/:id", updateTodo);

router.delete("/:id", deleteTodo);

module.exports = router;

```
## Defining the methods for our endpoint

The methods for the endpoints will be defined in the controllers’ folder.

The first step is to import the todo models.

```javascript
const Todo = require("../models/todo.models.js");

```

**listAllTodo()** : find() method will return all the todo inside the MongoDB collections.

```javascript
exports.listAllTodo = (req, res) => {
  Todo.find()
    .then((todo) => {
      console.log({ todo });
      res.json(todo);
    })
    .catch((err) => {
      res
        .status(404)
        .json({ message: "There isnt any todo available", error: err.message });
    });
};

```

**createTodo():** The method create() will create a todo item and return a success message.

```javascript
exports.createTodo = (req, res) => {
  Todo.create(req.body)
    .then((todo) => {
      console.log({ todo });
      res.json({
        message: "Cheers!! You have successfully added TODO",
        todo,
      });
    })
    .catch((err) => {
      res.status(404).json({
        message: "Sorry your todo list cannot be added",
        error: err.message,
      });
    });
};

```

Full article available here => https://aviyel.com/post/1150

Follow [@aviyelHQ](https://twitter.com/AviyelHq) or [sign-up](https://aviyel.com/discussions) on Aviyel for early access if you are a project maintainer, contributor, or just an Open Source enthusiast.

Join Aviyel's Discord => [Aviyel's world](https://discord.gg/TbfZmbvnN5)

Twitter =>[https://twitter.com/AviyelHq](https://twitter.com/AviyelHq)