Node.js: Accessing the MongoDB Database using Node.js for Performing CRUD Operations with Async/Await Approach

In this article, we will understand an approach for building a Node.js application for performing CRUD Operations by accessing the MongoDB database. In recent days I have come across several requirements from students regarding the MEAN and MERN JavaScript full-stack applications. Considering such a frequent requirement from my students I thought to write a post on it for the latest version of Node.js, MongoDB, and Mongoose packages.   

The Node.js can be downloaded from the following link

https://www.nodejs.org

The MongoDB Can be downloaded from the following link

https://www.mongodb.com/try/download/community

The code for this article is written using Microsoft Visual Studio Code (VSCode).

Step 1: Open Command Prompt (or Terminal Window) and create a new folder named node-api. Open this folder in VS Code. 

Step 2: Run the following commands to create a generate package.json file for the project

npm init -y

After generating package.json, run the following command to install Express, Mongoose, and MongoDB packages

npm install express mongoose mongodb

Step 3: In the project folder add a new file and name it dbconnection.js. In this folder, add the code as shown in Listing 1. This code establish connection with MongoDB database and define a schema for the collection which will be used to store products documents.

import mongoose from "mongoose";

mongoose.Promise = global.Promise;

mongoose.connect("mongodb://localhost/productsdb", {
    useNewUrlParser:true
});

const productSchema = new mongoose.Schema({
    ProductId:{
        type: String
    },
    ProductName:{
        type: String
    },
    Manufacturer:{
        type: String
    },
    Description:{
        type: String
    },
    Price:{
        type: Number
    }
});

const Products = mongoose.model('productsdb',productSchema);

export {Products}


Listing 1: The MongoDB Connection

As shown in Listing 1, we are using the Mongoose object and its methods like connect(), Schema(), and model() to establish a connection with the database, define the Collection schema, and establish a mapping between schema and the collection respectively. The Products is the model mapping that will be used to perform CRUD Operations   

Step 4: In the project folder, add a new file and name it as dataaccess.js. In this file, we will add code for performing CRUD Operations with the MongoDB Database.   As discussed in Listing 1, the Products model has the following methods for performing the CRUD Operations

  • create(), a method to create a new JSON document in the collection
  • findByIdAndUpdate(), a method to search a document based on ID and update it.
  • findOneAndRemove(), a method to search the record based on ID and remove it from the collection.
  • find(), this is an overloaded method, if no parameter is passed to it, then all documents will be returned else based on the condition passed using the JSON object the document will be returned from the collection.
The code in Listing 2, shows the code for CRUD Operations


import { Products } from "./dbconection.js";
 
export default class DataAccess {
    constructor(){

    }
     getProducts=async(req,resp)=>{
        const query = Products.find({}); 
        const products = await query.exec();
        resp.send( 
            products
         );
    }
    getProduct=async(req,resp)=>{
        console.log(`in API id = ${req.params.id}`);
        const id = req.params.id; 
        const product = await Products.find({_id:id});  
        resp.send( 
            product[0]
           );
    }
    createProduct=async(req,resp)=>{
         
        const product = {
            ProductId:req.body.ProductId,
            ProductName:req.body.ProductName,
            Manufacturer:req.body.Manufacturer,
            Description:req.body.Description,
            Price:parseInt(req.body.Price)
        };
        const result = await Products.create(product);
        resp.send( 
            result
        );
    }
    updateProduct=async(req,resp)=>{
        
        const id = req.params.id; 
        const product = {
            ProductId:req.body.ProductId,
            ProductName:req.body.ProductName,
            Manufacturer:req.body.Manufacturer,
            Description:req.body.Description,
            Price:parseInt(req.body.Price)
        };
        const result = await Products.findByIdAndUpdate({_id:id},product, {new:true});
        resp.send( result
          );
    }

    deleteProduct=async(req,resp)=>{
        const id = req.params.id; 
        console.log(`in rest delete id = ${id}`);
        const res =  await Products.findOneAndRemove({_id:id});
        resp.send(res
          );
    };

};

Listing 2: The code for performing CRUD operations      

The code in Listing 2 shows the DataAccess class. This class contains code for using the Mongoose models for performing CRUD Operations. Note that, all the methods performing CRUD operations are asynchronous, that's why we are using async/await approach for operations. Each method of this class accepts the Request and Response objects. These are the objects from the RequestHandler object that represent the HTTP Request and Response objects for processing the HTTP Requests received by the Express REST API methods.  

Step 5: In the project folder, add a new file and name it as server.js. In this file, we will add code for creating and exposing REST APIs using Express on port 9078. The code in Listing 3 shows the REST APIs.


import express from 'express';
import DataAccess from './dataaccess.js';

const app = express();

const da = new DataAccess();

const port  = process.env.PORT || 9078;

app.use(express.json());

app.get('/api/products', da.getProducts);

app.get('/api/products/:id', da.getProduct);

app.post('/api/products', da.createProduct);

app.put('/api/products/:id',da.updateProduct);

app.delete('/api/products/:id', da.deleteProduct);


app.listen(port, ()=>{
    console.log(`Server Started on PORT ${port}`);
});

Listing 3: The REST API Code

The code in Listing 3 shows REST APIs using HTTP Methods of the Express object. Each of these methods invokes CRUS methods from the DataAccess class that we have seen in Listing 2.  


Step 6: Modify the package.json to run the Node.js with the support for the ES 6 module that supports import and export statements. The modification is shown in Listing 4 

"type": "module",

Listing 4: The package.json modification for running the application    


Run the application from the Command Prompt by using the following command

npm server.js

Open the Postman or any other REST client and enter the following URL

http://localhost:9078/api/products

The Response will be empty but the database and collection will be created as shown in Figure 1 (You can install MongoDB Extension and connect to it or else you can install the MongoDB Compass)



Figure 1: The database and collection

Make the POST request as shown in Figure 2



Figure 2: The POST Request  

Click on the Send button. You will see the new JSON Document has been created. The newly created JSON Document can be seen from the MongoDB VSCode extension as shown in Figure 3



Figure 3: The Newly created document

 

Similarly, the PUT and DELETE requests can also be tested.

The code for this article can be downloaded from this link.

Conclusion: Node.js with EXPRESS REST APIs with new asynchronous programming is easier with a simple coding approach.  

 

 


 

 






Popular posts from this blog

Uploading Excel File to ASP.NET Core 6 application to save data from Excel to SQL Server Database

ASP.NET Core 6: Downloading Files from the Server

ASP.NET Core 6: Using Entity Framework Core with Oracle Database with Code-First Approach