Share:

M

Mayur Nalwala

Aug 04, 2022

CRUD app using Node.JS, Express & MongoDB

CRUD app using Node.JS, Express & MongoDB | Mayur Nalwala
This code along article will help beginners to get started with the basics of node.js and build restful APIs with proper standards and structure.

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.
note: This article might look lengthy but that’s just because I used a lot of screenshots. Beginners often struggle with the MongoDB Cloud Setup and a few other tasks so images will make things a bit clear. So for a better experience try to read this article on a Laptop or a Desktop.

What we’re building :

The following web application :P . . .
CRUD app using Node.JS, Express & MongoDB | Mayur Nalwala

Get Started:

CRUD app using Node.JS, Express & MongoDB | Mayur Nalwala
Create two sub-folders “ BackEnd” & “ FrontEnd”.
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.
CRUD app using Node.JS, Express & MongoDB | Mayur Nalwala

Terminal and package.json file

The package.json file contains all dependencies and scripts to run the project.

Next, we will create other required files for our project.
CRUD app using Node.JS, Express & MongoDB | Mayur Nalwala
We start with server.js, app.js & .env.
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.js
this file will have all the application level configuration,
as we go ahead we will keep on adding middlewares and
supporting libraries
*/
const express = require('express');
const app = express();
// create a base route with a response
app.get('/', (req,res) => {
res.send('server running');
})
module.exports = app
next we will configure our server.js file as follows:
/*
server.js
this file will have all the server configuration,
DB Connections, Port settings etc
*/
const app = require('/app);
// start server at port 3000
const server = app.listen(3000, () => {
console.log('Express Running on PORT 3000' )
})
next we configure package.json and start our server.
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"
}
}
run “npm start” on your terminal and you have a node express server up and running on http://localhost:3000/.

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.
    CRUD application mock design
  • 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.
    CRUD application mock design

    Create your first cluster

    CRUD application mock design

    make sure its a free cluster

  • Create a user for Database Access. On the left sidebar under “SECURITY” click on Database Access.
    CRUD application mock design
  • Add New User.
    CRUD application mock design
    CRUD application mock design

    Create a username and password

    Please remember the username and the password as we will be using it for our Cluster and DB connection.
  • Install MongoDB Compass MongoDB Compass GUI tool to manage our Database.
  • Once your cluster is ready, click connect.
    CRUD application mock design

    Connecting to our DB Cluster

    First, we need to do some firewall setting so that our DB is accessible to multiple IP’s.
    CRUD application mock design
    Select Add a Different IP Address and type 0.0.0.0/0, this will allow access to all the IP’s.
    CRUD application mock design

    Whitelisting IP’s

    After adding the IP address, we choose a connection method.
    CRUD application mock design
    Select the 2nd option, this will give us a connection string which we can use in the Compass GUI and our application.
    CRUD application mock design

    Cluster connection URL

    We can configure the connection URL as per our application. As we are working in Node.js, we choose the drivers as shown above.

    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.
    CRUD application mock design

    Connecting the cluster in MongoDB compass

    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”.

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”'
    CRUD application mock design

    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.
    CRUD application mock design
    CRUD application mock design
    CRUD application mock design
    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.
    CRUD application mock design
  • 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.js
    const mongoose = require('mongoose');
    require('dotenv').config({ path: '.env' });
    // Database connection
    mongoose.connect(process.env.DATABASE,
    {
    useUnifiedTopology: true,
    useNewUrlParser: true
    }
    );
    mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
    mongoose.connection.on('error', (err) => {
    console.error('Database Connection Error');
    });
    // require app.js
    const app = require('./app');
    // start the server on port 3000
    const 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.
A Schema is a JSON object that allows you to define the shape and content of documents and embedded documents in a collection.
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.

open “app.js” and do the following changes :
// app.js
const express = require('express'); // import express
const app = express(); // initialise app with express
const 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 posts
app.get('/getPosts', (req, res) => {
const posts = await Posts.find();
res.json(posts);
})
// export the app
module.exports = app;
first, we require “mongoose”, this is to create our schema.
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.
CRUD application mock design

use JSON formatter to prettify the raw data

In the next articles, we will structure our application in a proper MVC format and build the rest of our application.

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. :)

More from Author

Understanding CSS Positioning: A Step-by-Step Guide.
Understanding CSS Positioning: A Step-by-Step Guide.
CSS animated burger menu button.
CSS animated burger menu button.
Blog Template using NextJs, Typescript and Tailwind CSS.
Blog Template using NextJs, Typescript and Tailwind CSS.

Share:

Copyright © 2023 Web Expe

Privacy PolicyTerms and Conditions