Best Online Tutorials

SQL Tutorial

Free SQL Tutorial

SQL Interview Questions

SQL Practice Questions

SQL Tips & Tricks

SQL Errors

SQL Books

Angular Tutorial

Free Angular Tutorial

Angular Interview Questions

Angular Practice Questions

Angular Tips & Tricks

Angular Errors

Angular Books

Node.js Tutorial

Free Node.js Tutorial

Node.js Interview Questions

Node.js Practice Questions

Node.js Tips & Tricks

Node.js Errors

Node.js Books

React.js Tutorial

Free React.js Tutorial

React.js Interview Questions

React.js Practice Questions

React.js Tips & Tricks

React.js Errors

React.js Books

SSIS Tutorial

Free SSIS Tutorial

SSIS Interview Questions

SSIS Practice Questions

SSIS Tips & Tricks

SSIS Errors

SSIS Books

SEO Tutorial

Free SEO Tutorial

SEO Interview Questions

SEO Practice Questions

SEO Tips & Tricks

SEO Errors

SEO Books

Javascript Tutorial

Free Javascript Tutorial

Javascript Interview Questions

Javascript Practice Questions

Javascript Tips & Tricks

Javascript Errors

Javascript Books

MongoDB Tutorial

Free MongoDB Tutorial

MongoDB Interview Questions

MongoDB Practice Questions

MongoDB Tips & Tricks

MongoDB Errors

MongoDB Books

Next.js Tutorial

Free Next.js Tutorial

Next.js Interview Questions

Next.js Practice Questions

Next.js Tips & Tricks

Next.js Errors

Next.js Books

Create Rest API using Node.js Express.js and Mongodb 

Prashant Surya  |   Dec 1, 2019  |  Views: 1532
pictures

Description:

If you are new in Node.js API, you are at a good place to learn how to start creating rest API using Node.js express.js and mongodb in step by step in a simple way. 

Lets have a quick look into the overview of theses technical terms:

What is Node.js?
Nodejs is a JavaScript runtime web application framewok built on Google Chrome's V8 JavaScript engine.


What is Express.js:
Expresss.j is a web application framework for Node.js to develop restful API, and web application.


What is MongoDB?
MongoDB is a document-oriented NoSQL database, which stores data in JSON-like documents with schema called BSON.


What is Mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. 

It creates relationships between data and provides schema validation, also used to translate between objects in code and the representation of those objects in MongoDB


What is API?
Application program interface (API) is a set of routines, protocols, and tools for building software applications.


Now how to start creating the API using all these ?

First we should decide what to make in API, so lets start creating a API for the CRUD for "Users" table. Means we are creating an API to Create / Read / Update / Delete records from the Users table.

Step 1 : Installation 


Node.js

First you have to install Node.js on your system, then verifyy the version from command

node -v
Then check the version for npm (Node Package manager)

npm -v
You will get version as output of the installed Node.js and npm.

You also need a IDE for the development of the API. There are lots of IDE available , you can install anyone.


IDE:
My suggestion is to use VSCode, you can easily install and use it for free.


MongoDB:
Install MongoDB on your local machine or create your development login on mLAb


Step 2 : Add Package.json



First create folder and open it with VSCode IDE, and open its terminal to type commands.

npm init
This command with create a package.json file for you in the same folder.


Step 3: Add dependency libraries



npm install express --save
npm install mongoose --save
npm install body-parser --save

Step 4: Add server.js


Create the folder structure like this and add the following files named as below in root of your application folder.

-models/
-user.js
-routes/
API/
  -user.js
-server.js


Then in your server.js file import the required libraries.


const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');


// Add Body parser to covert request response to json
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }));


// DataBase configure
const dbURL = "mongodb://127.0.0.1:27017/demo"   //url of your database local/server


//Connect to MongoDB
mongoose
	.connect(dbURL)
	.then(() => console.log("MongoDB connected"))
	.catch(err => console.log(err));



//Run your web API on any port 
const port = process.env.PORT || 8000;
app.listen(port, () => {
	console.log("server running port", port);
});

Step 5: Test your application

 
IN your vscode terminal write command

node server.js
If every thing goes wright , it will show the running URL with the port 8000 "http://localhost:8000"

Now open this URL in your browser, your application is working now, with database connected.

You can see the console message on your terminal, like database connected / running on port  8000


Step 5: Add user schema model


Now in the file models/user.js add the following code for mongoose schema of user table, which will be created run-time in your mongoDB database.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//create User Schema 
const UserSchema = new Schema({
name: { type: String, require: true },
email: { type: String, require: true },
password: { type: String, require: false },
Id: { type: String, require: false },
Role: { type: String, require: false },
Address: { type: String, require: false },
Phone: { type: String, require: false },
Photo: { type: String, require: false },
CreatedBy: { type: String, require: false },
listingDtae: { type: String, default: Date.now },
CreatedOn: { type: Date, default: Date.now },
ModifiedBy: { type: String, require: false },
ModifiedOn: { type: String, require: false },
IsActive: { type: Boolean, require: false, default: true }
});
module.exports = User = mongoose.model('user', UserSchema);

Step 6: Add user CRUD API:



Now in the routes/api/user.js file add the following CRUD operation with HTTP verbs:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('../../models/user');


// Get users list
router.get('/list', (req, res) => {
  sortObj = {
    CreatedOn:-1,
}
  User.find({}).sort(sortObj).then(user => { res.json(user) });
})



// route GET api/users/count----total user
router.get('/count', (req, res) => {
  User.find({}).count().then(user => { res.json(user) });
})


// route POST api/users/add
router.post('/add', (req, res) => {
  User.findOne({ Id: req.body.email }).then(user => {
    if (user) {
      errors.email = 'Email already exists';
      return res.status(400).json(errors);
    } else {
      const newUser = new User(req.body);
      newUser
        .save()
        .then(user => {          
          res.json(user);
        })
        .catch(err => console.log(err));
    }
  });
});


// route GET api/users/list/:id
router.get('/list/:id', (req, res) => {
  User.findOne({ _id: mongoose.mongo.ObjectId(req.params.id) }).then(user => { res.json(user) });
})


// route POST api/users/update/:id
router.put('/update/:id', (req, res) => {
  User.findByIdAndUpdate(mongoose.mongo.ObjectId(req.params.id), { $set: req.body }, function (err, user) {
    if (err) return res.status(400).json(err);
    return res.status(200).json({ msg: "success" });
  });
});


// route GET api/User/count
router.get('/count', (req, res) => {
  User.count().then(c => { res.json(c) });
})

router.delete('/delete/:id', (req, res) => {
  User.findByIdAndDelete(mongoose.mongo.ObjectId(req.params.id)).then(user => res.json(user))
    .catch(err => console.log(err));
});


module.exports = router;

Step 7: Add user API routes in server.js


Add these two lines in your server.js , before the port listen lines 

const user = require('./routes/api/user');
app.use('/api/users', user);
So in the last the server.js code will be like


const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');


// Add Body parser to covert request response to json
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }));


// DataBase configure
const dbURL = "mongodb://127.0.0.1:27017/demo"   //url of your database local/server


//Connect to MongoDB
mongoose
	.connect(dbURL)
	.then(() => console.log("MongoDB connected"))
	.catch(err => console.log(err));

const user = require('./routes/api/user');
app.use('/api/users', user);


//Run your web API on any port 
const port = process.env.PORT || 8000;
app.listen(port, () => {
	console.log("server running port", port);
});

Step 8: Run and Test API with postman:


Run the below command and test your CRUD operations, using postman tool.

node server.js



Summary:

I have discussed today the very basic setup to start a API in Node.js with Express.js and MongoDB. I hope this will be helpful for the beginner to understand and setup their own code with the hep of this article.

We have create Node.js tutorial on DritalConnect.com with interview questions and  examples.

You can find out more trips and tricks from me regarding Node.js or MEAN Stack there.



My Suggestions to Read:


 


About Author:

I am a software developer, expert in MEAN Stack. I work as a consultant for MEAN stack on-page SEO, Angular universal SSR, micro-services architecture, performance, docker/nginx deployment, load balancing, cluster, security and on much more. 

Comments:
Content Contributor
Prashant Surya

Prashant Surya

Software developer at Uniserve Data Technologies Pvt. Ltd.  |   Noida, Uttar Pradesh, India

I am a software developer, freelancer and trainer working on technologies likes. MEAN stack, MERN Stack, ASP.NET full stack, WebRTC, socket.io ,PWA, SQL, JavaScript, jQuery, HTML, CSS, SEO, responsive UI/UX designing... having 7 years of experience in development in multiple domains like, eCommerce, RTA, capital markets, education, real estate...


Read related articles

Deploy your first Node.js App on Heroku for free

Prashant Surya  |   Jan 22, 2020  |  Views: 1202

How to add google adsense in angular universal

Prashant Surya  |   Dec 2, 2019  |  Views: 2138

Want to sell your software ?-

If you want to sell your readymade software to the genuine clients or businessman, list your software with details and demo links.

  • Sell ERP
  • Sell Website Clones
  • Sell App Clones
  • Sell Readymade Portals
  • Sell Readymade Websites
  • Sell Mobile Apps
  • Sell Window Apps

Clients will find it using our advanced search filter and will contact you directly.

No any charge for the product lsiting.

Do you own a Company ?+

Property.sale

Buy or Sell Commercial Property+

Are you a freelancer ?+

Looking for a job ?+

Are you a Service Provider ?+

Are you a blogger ?+

Do you own an IT Institute ?+



Property.sale