M
Mayur Nalwala
Aug 04, 2022
CRUD app using Node.JS, Express & MongoDB

Prerequisites :
- Knowledge of HTML, CSS / SCSS, JavaScript / jQuery as we will be using these for the front-end part of our application.
- JavaScript Fundamentals like promises, async-await, DOM manipulation will also help.
- Curiosity, interest and a tiny bit knowledge of Node.js, also you need to have node installed on your system. For detailed explanations and installation guide please refer to the following article.
Tools I Use :
- A code editor. I prefer Visual Studio Code as it gives me a complete environment and can be customized as required. Also, it’s the best :P . . .
- JSON Formatter browser extension to prettify the raw into a readable format.
What we’re building :
The following web application :P . . .
Get Started:

The BackEnd will have our Node.Js backend application which will serve REST APIs.
The FrontEnd will have the web application which will consume the APIs, similar to a real-world scenario.
Open your terminal in the BackEnd folder and run “npm init”, this initializes and creates a new node package with the details like package name description author, etc.
One important thing here is it will ask for the entry point i.e. from which file your application will start. Ideally, it is named index.js or server.js. I named it server.js as I do all my server configuration in this file.

Terminal and package.json file
Next, we will create other required files for our project.

server.js is the main entry point of our project. Here we will make our DB connections, import our app.js and start our server.
app.js will have the project configurations.
.env is a private file where we keep all our important and non-public things like DB connection links or API keys etc.
Let’s configure our application in app.js, we need to install Express: “npm install express”. After running this command, express will be added to your project environment and in the package.json dependencies.
now we will configure our app.js as follows:
/*app.jsthis file will have all the application level configuration,as we go ahead we will keep on adding middlewares andsupporting libraries*/const express = require('express');const app = express();// create a base route with a responseapp.get('/', (req,res) => {res.send('server running');})module.exports = app
/*server.jsthis file will have all the server configuration,DB Connections, Port settings etc*/const app = require('/app);// start server at port 3000const server = app.listen(3000, () => {console.log('Express Running on PORT 3000' )})
Install “nodemon”, a dependency for our server. With nodemon, we do don’t need to restart our server after every change, nodemon watches our application and restarts our server every time we save any file.
// package.json{"name": "nodejs-crud-app","version": "1.0.0","description": "Basic CRUD application with nodejs mongodb expressjs","main": "server.js","scripts": {"prod": "node server","watch": "nodemon server --ignore public/","start": "npm run watch"},"author": "Mayur Nalwala","license": "ISC","private": true,"dependencies": {"express": "^4.17.1","nodemon": "^2.0.2"}}
MongoDB Setup:
- Go to MongoDB Atlas Cloud service page and create an account and login.
- Select the Shared Cluster i.e the free plan option.
- Select the Cluster tire and create a Cluster. Mostly all the free options will be selected already (if it is a new account or you don’t have any clusters running) just make sure the M0 Sandbox is selected.
Create your first cluster
make sure its a free cluster
- Create a user for Database Access. On the left sidebar under “SECURITY” click on Database Access.
- Add New User.Please remember the username and the password as we will be using it for our Cluster and DB connection.
Create a username and password
- Install MongoDB Compass MongoDB Compass GUI tool to manage our Database.
- Once your cluster is ready, click connect.First, we need to do some firewall setting so that our DB is accessible to multiple IP’s.
Connecting to our DB Cluster
Select Add a Different IP Address and type 0.0.0.0/0, this will allow access to all the IP’s.After adding the IP address, we choose a connection method.Whitelisting IP’s
Select the 2nd option, this will give us a connection string which we can use in the Compass GUI and our application.We can configure the connection URL as per our application. As we are working in Node.js, we choose the drivers as shown above.Cluster connection URL
Paste the URL in the Compass GUI Tool and replace the <password> with the password we created while creating a user for the DB access and click connect.Note: One important thing to notice here is the Connection URL. By default, MongoDB creates a “test” database in our cluster. Next, we will create a database called “node_crud” and replace it with “test”.Connecting the cluster in MongoDB compass
Creating our Database:
- Open Compass and connect to your cluster. You can find your recent connection on the left sidebar.
- After connecting, create a new database “node_crud” and a new collection “posts”'
Creating DB and Collection
- We will add some dummy data in our collection. Click on “node_crud” and then click on “posts” collection.
- Inside posts collection, we will insert documents.now we have 2 documents (or tuples) in our database collection (i.e table).
Connecting our Node Application to the database:
Next, we will connect our node application to our database and create our first route to get the two documents from our posts collection.- in the .env file create a variable DATABASE and assign it to the DB connection URL. Make sure you add your password and replace test with node_crud in the connection URL.
- next we will configure our server.js file for our DB Connection. Open your terminal and run the following command “npm i mongoose dotenv”. mongoose is used to connect to our MongoDB and dotenv is for reading our env file.
next, configure the server.js file as follows.// server.jsconst mongoose = require('mongoose');require('dotenv').config({ path: '.env' });// Database connectionmongoose.connect(process.env.DATABASE,{useUnifiedTopology: true,useNewUrlParser: true});mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promisesmongoose.connection.on('error', (err) => {console.error('Database Connection Error');});// require app.jsconst app = require('./app');// start the server on port 3000const server = app.listen(3000, () => {console.log('Express running → PORT 3000');})
Creating our first GET API:
Before we create the first route and query our collection, we will be creating our Schema.We use schema to tell our application what type of data to expect and we use the schema to read and write data from a collection.A Schema is a JSON object that allows you to define the shape and content of documents and embedded documents in a collection.
open “app.js” and do the following changes :
// app.jsconst express = require('express'); // import expressconst app = express(); // initialise app with expressconst mongoose = require("mongoose");const PostsSchema = new mongoose.Schema({title: {type: String;},author: {type: String;},desc: {type: String;}})let Posts = mongoose.model('posts', PostsSchema);app.get('/', (req, res) => {res.send('Server Running');})// route to get postsapp.get('/getPosts', (req, res) => {const posts = await Posts.find();res.json(posts);})// export the appmodule.exports = app;
next, we declare a constant and create our schema with “mongoose.Schema”.
The title, author and desc are the properties of our document (created while inserting dummy data above).
next, we create our model using “mongoose.model” and pass the collection name and our schema as the parameters.
and finally, we create our route “/getPosts”.
in the get() method, we pass the route “/getPosts” as the first parameter and the second parameter is a callback function.
with the find() method we query our database using our schema and assign it to a variable.
and finally, we send the variable as a JSON response using res.json() and that is it, you have your first REST API ready.
run “npm start” on your terminal and go to the getPosts route http://localhost:3000/getPosts and you will get the posts collection data in a JSON format.

use JSON formatter to prettify the raw data
If you have any queries feel free to write it on our discussion page . Also, please leave a star on our github repo if this article helped you. Thank You. :)