How To Build Simple RESTful CRUD API With NodeJS, ExpressJS And MongoDB

Rahul Gupta
9 min readNov 18, 2019

--

Photo by Fortis Fotopoulus on Unsplash

We’ll be start to build a RESTful CRUD (Create, Read, Update, Delete) API with Node.js, Express and MongoDB. Here we’ll use Mongoose for interacting with the MongoDB instance.

Required applications

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications.

ExpressJS is one of the most popular web frameworks for node.js. It is built on top of node.js http module, and adds support for routing, middleware, view system etc. It is very simple and minimal, unlike other frameworks that try do way to much, thereby reducing the flexibility for developers to have their own design choices.

Mongoose is an ODM (Object Document Mapping) tool for Node.js and MongoDB. It helps you convert the objects in your code to documents in the database and vice versa.

Before proceeding to the next section, Please install MongoDB in your machine if you have not done already. Checkout the official MogngoDB installation manual for any help with the installation.

Postman is an API(application programming interface) development tool which helps to build, test and modify APIs.It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH etc.).

IDE (integrated development environment) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools, and a debugger — Wikipedia.

Environment check and setup

We have check that required applications are installed or not. We’ll check Node, NPM and MongoDB to installed on machine. Now open your preferred terminal / command prompt to run.

Let’s check the node version on machine, run the below command and see the output

node -v

Now Let’s check node package manager(npm) version and see the ouput

npm -v

Finally check MongoDB version and see the output

mongo -version

Creating Our Project

Now we’ll create our project. First of all choose filesystem / drive on where we’ll create our project. After that we create a directory name NodeExpressAPI. Then navigate to NodeExpressAPI directory. Command are as below

// Create directory for new project named NodeExpressAPI
mkdir NodeExpressAPI
// then Navigate to NodeExpressAPI
cd NodeExpressAPI

Now initialise the node js using npm init

npm init

That will ask a few thing like project name, version, description, author name etc follow the setup, if you do not to add info manually then use npm init -y which will geneate package.json file automatically.

After adding the info to command prompt finally accept the licence and you have write yes Then package.json will be created. Finally package.json will look like as below

Install express and other dependencies

Now we have to install express, body-parser, mongoose and nodemon modules in our application. Let’s install them by following in single command:

npm install express body-parser mongoose nodemon --save

Now package.json look like below and --save~ will add in the dependencies in our project. Nodemon auto restart the server after changes in files.

Setting up the web server

As we earlier we have created enter point of application is server.js, we will create server.js file.

touch server.js

Now create web server using express now server.js file look like

const express = require('express');const bodyParser = require('body-parser');// create express appconst app = express();// Setup server portconst port = process.env.PORT || 4000;// parse requests of content-type - application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: true }))// parse requests of content-type - application/jsonapp.use(bodyParser.json())// define a root/default routeapp.get('/', (req, res) => {  res.json({"message": "Hello World"});});// listen for requestsapp.listen(port, () => {  console.log(`Node server is listening on port ${port}`);});

Now run the server and go to http://localhost:4000to access the route. Response will like as below

Connect to the database

We’ll keep all the configurations for the app in a separate folder. Let’s create a new folder config in the root of our applications.

mkdir config
cd config

Now, Create a new file db.config.js inside config folder with the following piece code -

module.exports = {
url: 'mongodb://localhost:27017/node-express-api'
}

Now we have start the mongodb-server for that open another terminal/command prompt window and run the below command -

mongod

We’ll now import the above database configuration in server.js and connect to the database using mongoose.

Add the following piece code to the server.js file after app.use(bodyParser.json()) line :

node server.js

Now server.js file look like as below

const express = require('express');const bodyParser = require('body-parser');// create express appconst app = express();// Setup server portconst port = process.env.PORT || 4000;// parse requests of content-type - application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({ extended: true }))// parse requests of content-type - application/jsonapp.use(bodyParser.json())// Configuring the databaseconst dbConfig = require('./config/db.config.js');const mongoose = require('mongoose');mongoose.Promise = global.Promise;// Connecting to the databasemongoose.connect(dbConfig.url, {useNewUrlParser: true}).then(() => {  console.log("Successfully connected to the database");}).catch(err => {  console.log('Could not connect to the database.', err);  process.exit();});// define a root/default routeapp.get('/', (req, res) => {   res.json({"message": "Hello World"});});// listen for requestsapp.listen(port, () => {   console.log(`Node server is listening on port ${port}`);});

Now we’ll run the web server using nodemon. For that we can run

nodemon server.js

Even we do not need to add .js extension . Another way is add a line in package.jsonfile then we have can run nodemon start that will auto restart the server when do some changes in code.

// package.json file a few line snapshot
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1","start":"nodemon server" // add this line}

Now run in terminal

nodemon start

Create model in Mongoose

Now we’ll create model for that we make seperate directory for model, routes and controllers. Now create src/models at the root of project.

mkdir -p src/models
cd src/models

Now, create a file named user.model.js inside src/models folder with the following code -

touch src/models/user.model.js

Here is user.model.js file code -

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
first_name: String,
last_name: String,
email: String,
phone: String,
is_active: { type: Boolean, default: false },
is_verified: { type: Boolean, default: false },
is_deleted: { type: Boolean, default: false }
}, {
timestamps: true
});

module.exports = mongoose.model('User', UserSchema);

I have also added a timestamps option to the schema.

Mongoose uses this option to automatically add two new fields — createdAt and updatedAt to the schema.

Create routes using Express

Next we’ll setup the routes for the our APIs. Create a new folder called routes inside the src folder and also create user.routes.js file too inside src/routes directory.

mkdir src/routes
cd src/routes
touch user.routes.js

Now user.routes.js look like as

const express = require('express')const router = express.Router()const userController = require('../controllers/user.controllers');// Retrieve all usersrouter.get('/', userController.findAll);// Create a new userrouter.post('/', userController.create);// Retrieve a single user with idrouter.get('/:id', userController.findOne);// Update a user with idrouter.put('/:id', userController.update);// Delete a user with idrouter.delete('/:id', userController.delete);
module.exports = router

Note that We have added a require statement for user.controllers.js file. We’ll define the controller file in the next step. The controller will contain methods for handling all the CRUD operations for our api.

Before defining the controller, let’s first include the routes in server.js. Add the following require statement before app.listen() line inside server.js file.

// ........

// Require Users routes
const userRoutes = require('./src/routes/user.routes')// using as middlewareapp.use('/api/users', userRoutes)// ........

When we run the server we’ll get error when access users url api like

Error: Cannot find module '../controllers/user.controllers.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)

The error is because we have not created user.controllers.js file yet.

Create controllers in express

Next we’ll setup the controllers for the our APIs. Create a new folder called controllers inside the src folder and also create user.controllers.js file too inside src/controllers directory.

mkdir src/controllers
cd src/controllers
touch user.controllers.js

Now user.controllers.js file look like as

const User = require('../models/user.model.js');// Retrieve and return all users from the database.exports.findAll = (req, res) => {User.find()  .then(users => {  res.send(users);}).catch(err => {  res.status(500).send({  message: err.message || "Something went wrong while getting list of users."});});};// Create and Save a new Userexports.create = (req, res) => {// Validate requestif(!req.body) {  return res.status(400).send({  message: "Please fill all required field"});}// Create a new Userconst user = new User({  first_name: req.body.first_name,  last_name: req.body.last_name,  email: req.body.last_name,  phone: req.body.last_name});// Save user in the databaseuser.save()  .then(data => {  res.send(data);}).catch(err => {  res.status(500).send({  message: err.message || "Something went wrong while creating new user."});});};// Find a single User with a idexports.findOne = (req, res) => { User.findById(req.params.id)  .then(user => {
if(!user) {
return res.status(404).send({ message: "User not found with id " + req.params.id });} res.send(user);}).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "User not found with id " + req.params.id });}return res.status(500).send({ message: "Error getting user with id " + req.params.id});});};// Update a User identified by the id in the requestexports.update = (req, res) => {// Validate Requestif(!req.body) { return res.status(400).send({ message: "Please fill all required field"});}// Find user and update it with the request bodyUser.findByIdAndUpdate(req.params.id, { first_name: req.body.first_name, last_name: req.body.last_name, email: req.body.last_name, phone: req.body.last_name}, {new: true}).then(user => { if(!user) { return res.status(404).send({ message: "user not found with id " + req.params.id });}res.send(user);}).catch(err => {if(err.kind === 'ObjectId') { return res.status(404).send({ message: "user not found with id " + req.params.id});}return res.status(500).send({ message: "Error updating user with id " + req.params.id});});};// Delete a User with the specified id in the requestexports.delete = (req, res) => {User.findByIdAndRemove(req.params.id).then(user => {if(!user) { return res.status(404).send({ message: "user not found with id " + req.params.id});}res.send({message: "user deleted successfully!"});}).catch(err => {if(err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: "user not found with id " + req.params.id});}return res.status(500).send({ message: "Could not delete user with id " + req.params.id});});};

You can check out the documentation of all the methods that we used in the above APIs on Mongoose’s official documentation -

API end points

  1. GET /api/users: will give all users stored in database
  2. GET /api/users/<user_id>: will give a specific user with user_id.
  3. POST /api/users : user can create a new user
  4. PATCH /api/users/<user_id>: update a user partially
  5. DELETE /api/users/<user_id>: delete a user
  6. PUT /api/users/<user_id>: update a user completely

Now Time to set APIs in post

Creating a new user api/users using POST method

Get all users list /api/users using GET method

Get user by specific id api/users/user_id using GET method

Update user by specific id api/users/user_id using PUT method

Delete user by specific id api/users/user_id using DELETE method

Conclusion

In this story, we had learnt how to make APIs using Node, Express and MongoDB.

You can find here git repository.

https://github.com/rahulguptafullstack/NodeJsExpressApi

Thanks for reading. Hope it helps.

--

--

Rahul Gupta

Full Stack Developer | Python | Django | PHP | Laravel | Codeigniter | NodeJS | Angular | ReactJS | Flutter