Pages

How to Build a RESTful API Using Node Express and MongoDB- Part 1

In this blog, we will build a Rest API using Nodejs, Expressjs, and MongoDB. This is the first part where we will talk about the basics of building REST APIs with the help of NodeJS, ExpressJS, and MongoDB.  

Step 1: Run a command

Run the below command in an empty folder:

npm init


After running the command, it will ask you to enter various details. You need to enter project names, the repository, the author, and much more. It will generate a file name package.json in the folder.  

                                                  Source: FreeCodeCamp.org


{

  "name": "rest-api-express-mongo",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "echo \"Error: no test specified\" && exit 1"

  },

  "author": "",

  "license": "ISC"

}


The package.json file contains all the scripts such as how to test the application, and how to run the application, plus all the dependencies. This NodeJS REST API MongoDB you can built accordingly. 


Install some of the dependencies now:

npm i express mongoose nodemon dotenv

Step 2: Install and set up frameworks

  • Install NodeJS to restart the server every time you save the file.

  • ExpressJS is utilized as middleware to create multiple CRUD endpoints.

  • Mongoose is used for managing your data in MongoDB with the help of multiple queries. 

  • Dotenv helps you to manage a .env file. 


Make a file called index.js once they have finished installing. This will serve as our application's starting point.


Let's execute this file after adding Express and Mongoose.

const express = require('express');

const mongoose = require('mongoose');


Transfer all the Express contents into a new constant named app. 

const express = require('express');

const mongoose = require('mongoose');


const app = express();


const express = require('express');

const mongoose = require('mongoose');


const app = express();


app.use(express.json());


app.listen(3000, () => {

    console.log(`Server Started at ${3000}`)

})


After this, the server is set to Port 3000. In order to start our server we also need to add app.use. We have a piece of code that enables us to receive the JSON formatted data.


Include the following script in the package.json file:


"scripts": {

    "start": "nodemon index.js"

},


It also represents the way to start the server with the help of npm start, this will run with the help of Nodemon package that we installed earlier. 


Enter the npm in the terminal, and the following output will occur. 

                                               Source: FreeCodeCamp.org

Step 3: Configure the MongoDB Database

To configure the MongoDB Database, you need to log in to MongoDB or create your account, or sign in to the account. 


Sign in to the account, we need to create a database. 

                                            Source: FreeCodeCamp.org


Create a Free Shared Cluster.


You need to enter the username and password, so fill that information in. 

Now, add your IP Address.

                                                           Source: FreeCodeCamp.org


Press on the Finish button and close the window.

                                             Source: FreeCodeCamp.org


The process will take some time for the cluster to finish, so you need to wait. After this create a .env file in the folder. 


Now on the Home Page of Cluster, press on the connect button. 

                                              Source: FreeCodeCamp.org


The below image will appear:

                                                  Source: FreeCodeCamp.org


Press on the MongoDB Compass, and you will see the below string. Plus, install the MongoDB Compass.

                                               Source: FreeCodeCamp.org


This string that you have previously used should now include your username and password. The completed connecting string will resemble the following:


mongodb+srv://nishant:********@cluster0.xduyh.mongodb.net/testDatabase


The username, in this case, is ‘nishant’, the password comes next, and the database name comes last.


Paste this string into the.env file as a result.

DATABASE_URL = mongodb+srv://nishant:*******@cluster0.xduyh.mongodb.net/testDatabase


Add the string in MongoDB Compass. 


                                                Source: FreeCodeCamp.org


Now, press the connect button. 


You will get here two Databases by default. And later third one will be created automatically. 

                                                Source: FreeCodeCamp.org


After that, you need to import all the contents to .env file in the script file name index.js. 


require('dotenv').config();


const mongoString = process.env.DATABASE_URL


Now, we need to store the string into a mongoString variable. 


You need to connect the database to the server using Mongoose. 

mongoose.connect(mongoString);

const database = mongoose.connection


Now, depending on whether our database connection succeeds or fails, we must throw a success or an error message.

database.on('error', (error) => {

    console.log(error)

})


database.once('connected', () => {

    console.log('Database Connected');

})


Database.on in this case indicates that it will attempt to connect to the database and throw an exception if the attempt fails. And database.once indicates that it will only be run once. If it is successful, a notification that reads "Database Connected" will appear.

                                         Source: FreeCodeCamp.org


Below is the code from the start. This is the REST API example that will help you build it. 

require('dotenv').config();


const express = require('express');

const mongoose = require('mongoose');

const mongoString = process.env.DATABASE_URL;


mongoose.connect(mongoString);

const database = mongoose.connection;


database.on('error', (error) => {

    console.log(error)

})


database.once('connected', () => {

    console.log('Database Connected');

})

const app = express();


app.use(express.json());


app.listen(3000, () => {

    console.log(`Server Started at ${3000}`)

})


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...