Creating a CRUD app using Node.js, Express.js and MongoDB

Amal Jose
9 min readMar 20, 2020

Introduction

In this tutorial, we will create a basic CRUD (Create Read Update Delete) application using Node.js. We will use Express.js for routing and MongoDB to store our data.

Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a browser.
Express.js is one of the popular web frameworks for Node.js. It simplifies routing, creating middleware etc.
MongoDB is one of the most popular databases used by modern apps. It is an opensource, cross-platform NoSQL database.

In this tutorial, we’re going to build an address book which has the option for creating, updating and deleting a user.

Getting Started

Before we start creating the app, we need to make sure that Node.js and MongoDB are installed. If they are already installed ignore this step.

  1. Download Node.js and install
  2. To verify the installation, execute the following command in terminal
node -v

3. Download MongoDB and install

4. Refer to official MongoDB docs for help with the installation

5. To verify the installation, execute the following command in terminal

mongo --version

Let’s build the App

Initialising the app

  1. Create a directory called ‘AddressBook’ (you can name it whatever you want)
  2. Move to the directory we created and execute the following command
npm init

The above command creates a file called package.json inside the directory. this file contains the information about our Node project. This file is used by npm(Node Package Manager) to find the metadata about the application and manage the dependencies used by the application.

3. Install the dependencies used by the application

  • Express.js
  • body-parser -for parsing the incoming request
  • mongoose -used for object modelling

execute the command for installing the dependencies

npm install --save express body-parser mongoose

then our package.json file will look like this

So we’ve initialised our app and installed the required dependencies. Now let’s start coding the app.

Create the server

Create a file called index.js in the root directory(AddressBook). For initializing the server we use the listen method of express. A port number is a need for the server to work.

Following code creates a server and initializes it on port 3000.

const express = require('express')//Initialize express app
const app = express();
//Initialize the sever
app.listen(3000, () => {
console.log('sever listening on port:3000');
});

What the above code does is we initialize an express app and tells express to listen at port 3000 for the incoming requests.

For starting the server, execute the following command in terminal

node index.js

If sever is started successfully you will get the following output

We’ve successfully created and started a server now.

Connecting to DB

Before we config the database I’m assuming that you have installed MongoDB. You can use MongoDB Compass for GUI. Compass allows you to analyze and understand the contents of your data without formal knowledge of MongoDB query syntax.

We are using MongoDB to store our data. We need to config the DB in our application. For connecting to the database we use mongoose.

We should require mongoose in our app to do this. Mongoose is an Object Document Model (ODM) for Node.js

const mongoose = require('mongoose')

We use mongoose.connect method for connecting to DB. we should pass the connection URI inside the connect method.

Inside the index.js file copy the following code.

// Connecting to DBmongoose.connect('mongodb://localhost:27017/AddressBook', {useNewUrlParser: true, useUnifiedTopology: true
}).then(() => {
console.log('connected to db')
}).catch((error) => {
console.log(error)
})

27017 is the default port number of MongoDB. The part after the port number (AddressBook) is the name of the database.

If you got the following output you have successfully connected to DB.

Creating the schema

The schema defines the structure of our database. Schema helps to organize the documents in the collection. For creating the schema create a file called models.js inside a new folder called model . For creating the schema we require mongoose. import mongoose to models.js using the following code.

const mongoose = require('mongoose');

Since we are creating an address book, our schema should contain the following fields

  • name
  • email address
  • phone number
  • place

The schema for the data is created using the mongoose.Schema method. Type of data should be specified.

models.js should contain the following code.

// Schema for AddressBook
const addressSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
phone: {
type: Number,
required: true
},
place: {
type: String,
required: true
}
})
//Creating the collection Address
const Address = mongoose.model('Address', addressSchema)

The above code snippet creates an object model. type defines the type of the field and required is used to specify if it is mandatory to fill the field.

Then we export the schema that we created using the following code

module.exports = Address;

Define the routes

Routes define the way for handling client requests. User navigation to various URLs of the application is handled by routes. Routes take the following structure

app.METHOD(PATH, HANDLER)
  • app is the instance of express
  • METHOD is an HTTP request method. The different types of methods are GET, POST, PUT, DELETE and so on.
  • PATH is the path or the endpoint on the server.
  • HANDLER is the function executed when the endpoint is matched

let’s add the details of a user into the address book.

For adding details, we require the Address model we created. The following code does that.

const Address = require('./model/models')

The above code imports the schema to index.js from models.js .

For adding a user to DB we need to parse details from the incoming request. This is where body-parser is used. We should require body-parser in our app. We are sending the data in urlencoded form.

const bodyParser = require('body-parser')// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))

Since we don’t have a frontend, we’ll be using a rest client for sending the API request. In this tutorial, I’m using Insomnia. There are other REST clients like Postman. You can use whichever you prefer.

I’m assuming that before we test the app, make sure you started the app every time you saves it or there is a way we can automate the restarting process. It is done by a package called nodemon. it automates the restarting process. It restarts the app for us every time after we save our app.

You can install it as a dev dependency in our app. for installing it execute the following command in the terminal in your root directory.

npm install -g --save-dev nodemon

and for running the app, just execute this

nodemon index.js

that’s it, now nodemon automatically restarts every time after you save your app.

Adding a user details

For adding a user to DB, copy the code into your index.js.

// Adding a User to AddressBookapp.post('/', (req, res) => {
name = req.body.name,
email = req.body.email,
phone = req.body.phone,
place = req.body.place
let newAddress = new Address({
name: name,
email: email,
phone: phone,
place: place
})
newAddress.save().then((address) => {
res.send(address)
}).catch((err) => {
console.log(error)
})
})

What the above code does is that we send a post request which contains the data. req.bodycontains the data that we pass from the frontend. we parse the data using body-parser and pass it to the variables. then we create a new instance of the address model we created and saves it to DB using the collection.save method. Then the response is returned.

If the user was created successfully we will get the above response.

Now we have created a user. You can use MongoDB Compass to view the data in the DB. For connecting compass to DB use the connection string

mongodb://localhost:27017

select the DB AddressBook and you can view the user details in compass.

Reading user details

For every document created in MongoDB, there will an object id allocated by MongoDB and the object id will be unique. we use the object id for retrieving the user data from the database.

For retrieving a user from DB, copy the code into your index.js.

// Reading a Uder from AddressBookapp.get('/:id', (req, res) =>{
Address.findById(req.params.id, (err, user) =>{
res.send(user)
})
})

We pass in the object id of the user in the request and fetches the user with the corresponding object id. If there is a user with the object is we passed we will get the user as the response.

If we got the above response we read the user successfully from the DB.

Updating a User

For updating the user we will use the object id of the user. We pass the object id of the user as a parameter of the request. For updating user copy the following code into index.js.

// Updating the Userapp.post('/update/:id', (req, res) => {
let address = {}
if (req.body.name) address.name = req.body.name
if (req.body.email) address.email = req.body.email
if (req.body.phone) address.phone = req.body.phone
if (req.body.place) address.place = req.body.place
address = { $set: address }Address.update({_id: req.params.id}, address).then(() => {
res.send(address)
}).catch((err) => {
console.log(error)
})
})

In the above code, we create an object called address. then we check for the values passed from the request. if there is a value we will add the value to the address object. we use the field update operator $set to update the fields that have value. If the data is updated successfully we will receive the updated field as the response.

In the application, I’ve updated the phone number of the user named user1. I received the updated phone number as a response.

If we look at compass we can view the updated data.

Deleting a User

Deleting the user is also done using the object id of the user. For deleting the user we pass the object id of the user as a parameter of the request. For deleting the user copy the following code to the index.js.

// Deleting the User from AddressBookapp.delete('/delete/:id', (req, res) => {
Address.remove(_id: req.params.id).then(() => {
res.send('user deleted')
}).catch((err) => {
console.log(error)
})
})

In the above code, we pass the id of the user we want to delete in the request. if there is a user with object id we’ve passed, the user will be deleted from the DB and you will get the response as ‘user deleted’.

Now we had successfully deleted a user from our AddressBook.

Wrapping up

Done! we have created a simple CRUD (Create, Delete, Update, Delete) app using Node.js, Expess.js and MongoDB.

After completing the tutorial you learned to:

  • Create a server using express.js
  • to use MongoDB and compass
  • execute CRUD operations
  • use REST Clients like Postman and Insomnia

For the complete code of this tutorial, visit the following GitHub Repo.

If you have any doubts or suggestions, let me know in the comment section.

Thanks for reading the tutorial and HAPPY CODING 🎉🎉.

--

--