Performing CRUD in Mongodb with Expressjs

Learn via video courses
Topics Covered

Overview

In this article, we are going to learn about performing CRUD in Mongodb with Expressjs. Before getting started with the topic, let us get a short overview of the topic.

Performing CRUD in Mongodb with Expressjs: Performing CRUD operations in MongoDB with ExpressJS is a common requirement for building web applications. In expressJS CRUD is an essential operation, which refers to the four basic operations of persistent storage: Create, Read, Update, and Delete. Using these CRUD operations we can alter or make changes in the documents inside a collection of Mongodb database. These operations are essential in building web applications that interact with a database or any other data source. With ExpressJS, developers can easily implement CRUD functionality by defining routes that handle each operation and interact with the database through an ORM or other data access library.

So let us now begin with the main agenda of our article, performing CRUD in Mongodb with Expressjs.

Introduction

Performing CRUD (Create, Read, Update, Delete) operations in MongoDB with ExpressJS is a common requirement for building web applications. In order to begin using MongoDB, it is necessary to establish a connection between your ExpressJS application and the MongoDB database. This can be accomplished by employing a MongoDB driver, such as Mongoose, that works with Node.js. Once the connection is established, the Mongoose models can be utilized to create, read, update, and delete documents in the MongoDB collections.

To create a document, you can create a new instance of the Mongoose model and save it to the database. To read a document, you can use the find() method to search for documents that match a specific query or use the findOne() method to retrieve the first document that matches a query. To update a document, you can use the update() method or the findByIdAndUpdate() method to update an existing document. To delete a document, you can use the remove() method or the findByIdAndRemove() method to remove a document from the database.

To perform these operations in your ExpressJS application, you need to define routes that handle requests to perform CRUD operations. These routes will interact with the Mongoose models to create, read, update, or delete documents in the database. The ExpressJS application can also use middleware to validate input data, authenticate users, or perform other tasks before executing the CRUD operations.

Overall, performing CRUD operations in MongoDB with ExpressJS requires setting up the database connection, defining Mongoose models, creating routes to handle CRUD operations, and using middleware to handle additional tasks.

Create Node.js App

Node.js is a widely used runtime environment that is open-source and operates on Chrome's V8 JavaScript engine. It provides developers with the ability to create server-side JavaScript applications using the same programming language as client-side applications. Essentially, a Node.js app is an application developed utilizing Node.js runtime, which runs on a server.

To create a Node.js app, you need to follow these steps:

  1. Install Node.js on your machine:
    To install Node.js, you can visit its official website, where you will download its different compatible versions based on your operating system. The official documentation is also provided, which will guide you to get started with Node.js and its installation process.
  2. Create a new project directory:
    Open your terminal or command prompt and create a new project directory. You can do this by typing the command given below and pressing enter.
  1. Navigate to the project directory:
    Use the cd command to navigate into the project directory. You can do this by typing the command given below and pressing enter.
  1. Initialize the project:
    Run the command npm init to create a new package.json file. This file will contain all the dependencies and other project-related information.
  1. Install required modules:
    Use the npm install command to install the required modules for your project. For example, if you want to use the express module, mongoose, and Cors, you can run the following command and press enter.

The package.json file should look like this:

That's it! you have successfully created a Node.js application. Now, let us set up a server using the Express.js module.

Setup Express Web Server

An Express web server refers to a server constructed utilizing the Express.js framework, which is a frequently used and well-known framework for developing web applications in Node.js. Express offers a range of robust capabilities for managing HTTP requests and responses, including routing, middleware, and templating.

An Express web server can handle various types of CRUD requests such as GET, POST, PUT, DELETE, and more. It also provides a robust set of middleware functions that can be used to perform tasks such as authentication, logging, and error handling.

To set up the Express web server, we should follow these steps:

  1. Create the server file:
    Create a new JavaScript file in your project directory express-node-mongodb, for example, server.js. Open the file in your preferred code editor.
  2. Import the required modules:
    In the server.js file, import the express module and any other modules you need. For example, you might also want to import the body-parser module to handle HTTP request bodies.
  3. Define your server routes:
    In the server.js file, define your server routes. For example:
    This defines a route that responds to GET requests to the root URL with the text Hello, world!.
  4. Start the server:
    In the server.js file, start the server by listening to a specific port. For example:
    This starts the server and logs a message to the console indicating that it's running.
  5. Test the server:
    Open a web browser and visit http://localhost:3000. You should see the message Hello, world! displayed in your browser.

Congratulations, you have successfully set up an Express web server!

Configure MongoDB Database & Mongoose

Now, let us see a step-by-step guide on how to configure the MongoDB database and Mongoose:

  1. Install MongoDB:
  • Download the MongoDB Community Server from the official MongoDB website MongoDB
  • Once you have downloaded the installer, follow the installation instructions for your operating system.
  1. Start the MongoDB Server:
  • After installation, start the MongoDB server by running the mongod executable in your command line.
  • For example, on a Unix-based system, you can start the server with the following command:
    This will start the MongoDB server with the default data directory at /data/db.
  1. Create a MongoDB Database:

    • Connect to the MongoDB server using the mongo shell (you can do this by running the mongo executable in your command line).

    This will start the mongo shell, which is an interactive JavaScript interface to MongoDB.

    • To create a new database, run the following command:

    Replace <database_name> with the name you want to give to your database. For example, to create a database called product, run the following command:

  2. Install Mongoose:
    Mongoose is an Object-Document Mapping (ODM) library for MongoDB, which provides a higher level of abstraction over the MongoDB driver. To install Mongoose using npm, run the following command:

  3. Configure Mongoose:
    To use Mongoose in our Node.js application express-node-MongoDB, require Mongoose at the top of your server.js file, you can write the following code to import Mongoose in your application:

    After importing the Mongoosh, you can connect to your MongoDB database using Mongoose:

    Replace <database_name> with the name of your MongoDB database. In our case, it will be product.

    The useNewUrlParser and useUnifiedTopology options are recommended when using Mongoose to connect to MongoDB. useNewUrlParser uses the new MongoDB driver URL parser, and useUnifiedTopology enables the new Server Discovery and Monitoring engine, which provides better support for replica sets and sharded clusters.

Here's an example of our Node.js application express-node-MongoDB that uses Mongoose to connect to our MongoDB database:

Explanation:

  • At first, we imported the Mongoose library and assigns it to the Mongoose constant.
  • Then, we connect to the MongoDB database named product running on the local machine. The options useNewUrlParser and useUnifiedTopology are passed as arguments to the connect method to avoid deprecation warnings.
  • Then, we assign the mongoose.connection object to the db constant.
  • db.on('error', console.error.bind(console, 'connection error:')); - This line sets up an event listener on the db object to log any connection errors to the console.
  • db.once('open', function() { console.log("Connected to MongoDB database"); }); - This line sets up an event listener on the db object to log a success message to the console once the connection to the database is established for the first time.

Overall, this code sets up a connection to a MongoDB database and logs any errors or successful connections to the console.

Define Mongoose

Mongoose is a library for Node.js and MongoDB that utilizes Object Data Modeling (ODM) to provide a structured approach for modeling and managing data in MongoDB databases. It facilitates the definition of schema and models for MongoDB data, as well as provides various features for data validation, query building, middleware support, and more, all of which streamline the process of working with databases in Node.js applications. Additionally, Mongoose offers a wide range of tools for data manipulation, including CRUD operations, virtuals, indexes, hooks, and population, making it a popular choice for developers who wish to build powerful and scalable Node.js applications that are supported by a MongoDB backend.

As we have already defined Mongoose in our server.js file above, let us move to our next step of defining the Mongoose model.

Define the Mongoose Model

In an Express.js application that uses Mongoose, a model is a representation of a collection in MongoDB, and it defines the structure of the documents that will be stored in that collection. Here is an example of how to define a Mongoose model in our Express.js application express-node-MongoDB:

Create a Model Directory

Open your terminal or command prompt, move to your project directory with cd express-node-mongodb, and there create a new folder termed as a model. You can do this by typing the command given below and pressing enter.

Create a product.js file inside the model folder.

Project Structure

Our project structure will be similar to this:

Defining a Mongoose Model

Here is an example of how to define a Mongoose model for a Product collection in a product.js file in the model directory:

Explanation:

In this example, we first require Mongoose and then define a schema for our Product collection. The schema specifies the fields that will be stored in each document in the collection and their data types. In this case, we have defined three fields: name, description, and price, all of which are required.

After defining the schema, we use the mongoose.model() method to create a Mongoose model for our Product collection, and then export it so that it can be used in other parts of our Express.js application.

This Mongoose Model represents the Product collection in the MongoDB database. These fields will be generated automatically for each Product document: _id, name, description, price, createdAt, updatedAt, __v.

To make the Mongoose model compatible with a front-end that requires the use of the id field instead of _id, it is necessary to override the toJSON method that maps the default object to a custom object. Therefore, the modification of the Mongoose model may be achieved through the following code:

And the final result will look like this:

Create the Controller

In an Express.js application, a controller is responsible for handling user requests and returning appropriate responses. Here is an example of how to create a controller in our Express.js application express-node-MongoDB:

Create a Controller Directory

Open your terminal or command prompt, move to your project directory with cd express-node-mongodb, and there create a new folder termed controller. You can do this by typing the command given below and pressing enter.

Create a productController.js file inside the controller folder.

Project Structure

Our project structure will be similar to this:

In this structure, we have a directory structure with a controllers directory, which will contain our controller modules.

Implement CRUD Functionalities

Inside the productController.js file, let us implement these CRUD functionalities:

  • Create a new object
  • Retrieve objects (with the condition)
  • Retrieve a single object
  • Update an object
  • Delete an object
  • Delete all objects
  • Find all objects by condition

Code:

Explanation:

This is a module that exports various controller functions for CRUD (Create, Read, Update, Delete) operations on a database using the Mongoose ORM. The code uses asynchronous functions (async/await) to interact with the database.

The module exports the following functions:

  • createProduct:
    This function creates a new product by creating a new instance of the Product model (defined in the ../models/product module) using the data in the req.body object. The new product is saved to the database using the save() method of the model. If the operation is successful, the function responds with a JSON representation of the product and an HTTP status code of 201. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.
  • getProducts:
    This function retrieves all products from the database that match the conditions specified in the req.query object. The function responds with a JSON array of the products and an HTTP status code of 200. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.
  • getProductById:
    This function retrieves a single product from the database by its ID, which is passed in as a parameter in the URL. If the product is not found, the function responds with an error message and an HTTP status code of 404. If the product is found, the function responds with a JSON representation of the product and an HTTP status code of 200. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.
  • updateProduct:
    This function updates a single product in the database by its ID, which is passed in as a parameter in the URL, using the data in the req.body object. If the product is not found, the function responds with an error message and an HTTP status code of 404. If the update is successful, the function responds with a JSON representation of the updated product and an HTTP status code of 200. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.
  • deleteProduct:
    This function deletes a single product from the database by its ID, which is passed in as a parameter in the URL. If the product is not found, the function responds with an error message and an HTTP status code of 404. If the deletion is successful, the function responds with a success message and an HTTP status code of 200. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.
  • deleteAllProducts:
    This function deletes all products from the database. If the deletion is successful, the function responds with a success message and an HTTP status code of 200. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.
  • findProductsByCondition:
    This function retrieves all products from the database that match the conditions specified in the req.body object. The function responds with a JSON array of the products and an HTTP status code of 200. If there is any error occurs in the function, it will return an HTTP status code of 500 with an error message.

Overall, these controller functions provide the basic CRUD (Create, Read, Update, Delete) functionality for the Product model in our Express.js application using Mongoose.

Define Routes

In an Express.js application, routes are used to map incoming HTTP requests to specific controller functions.

Create a Routes Directory

Open your terminal or command prompt, move to your project directory with cd express-node-mongodb, and there create a new folder termed controller. You can do this by typing the command given below and pressing enter.

Create a products.js file inside the routes folder.

Project Structure

Our project structure will be similar to this:

In this structure, we have a directory structure with a routes directory, which will contain our router modules.

Here's an example of how to define routes for the Product model in our application express-node-MongoDB:

Code:

Explanation:

In this example, we define a new router using the express.Router() method. We then specify the various routes for the Product model using the router's HTTP methods (router.post(), router.get(), router.put(), and router.delete()). Each route maps to a specific controller function in the productsController.js file.

  • router.post('/products', productsController.createProduct):
    This route listens for a POST request with a URL of /products. When this route is accessed, it calls the createProduct function in the productsController.js file. This function creates a new Product object in the database with the data provided in the request body.
  • router.get('/products', productsController.getAllProducts):
    This route listens for a GET request with a URL of /products. When this route is accessed, it calls the getAllProducts function in the productsController.js file. This function retrieves all Product objects from the database and returns them as a JSON response.
  • router.get('/products/', productsController.getOneProduct):
    This route listens for a GET request with a URL of /products/:id, where id is the unique identifier of a specific Product object. When this route is accessed, it calls the getOneProduct function in the productsController.js file. This function retrieves the Product object with the specified id from the database and returns it as a JSON response.
  • router.put('/products/', productsController.updateProduct):
    This route listens for a PUT request with a URL of /products/:id, where id is the unique identifier of a specific Product object. When this route is accessed, it calls the updateProduct function in the productsController.js file. This function updates the Product object with the specified id in the database with the data provided in the request body.
  • router.delete('/products/', productsController.deleteProduct):
    This route listens for a DELETE request with a URL of /products/:id, where id is the unique identifier of a specific Product object. When this route is accessed, it calls the deleteProduct function in the productsController.js file. This function deletes the Product object with the specified id from the database.
  • router.delete('/products', productsController.deleteAllProducts):
    This route listens for a DELETE request with a URL of /products. When this route is accessed, it calls the deleteAllProducts function in the productsController.js file. This function deletes all Product objects from the database.
  • router.post('/products/search', productsController.findProductsByCondition):
    This route listens for a POST request with a URL of /products/search. When this route is accessed, it calls the findProductsByCondition function in the productsController.js file. This function retrieves all Product objects from the database that match a specified search condition, which is provided in the request body, and returns them as a JSON response.

By defining routes in this way, we can map incoming requests to the appropriate controller functions, and provide basic CRUD functionality for our Product model in our Express.js application.

Test the APIs

Now, we are done with the coding part, and now let us test the APIs we have created in our application. To test the APIs created in the Express.js application, you can use tools like Postman or cURL.

Here, let us test these APIs by using cURL:

Create a new product:

This will send a POST request with a JSON payload to the server at http://localhost:3000/products to create a new product with the name Product 1, description Good Product, and price 10. The server will then return the created product as a JSON object.

Retrieve all products:

This will send a GET request to the server at http://localhost:3000/products to fetch all the products. The server will then return all the created products as a JSON object.

Retrieve a single product:

Replace <product_id> with the actual ID of the product you want to retrieve.

This will send a GET request to the server at http://localhost:3000/products/<product_id> to fetch the product with the productId matches with <product_id>. The server will then return the product with the productId matches with <product_id> as a JSON object.

Update a product:

Replace <product_id> with the actual ID of the product you want to update.

This will send a PUT request with a JSON payload to the server at http://localhost:3000/products/<product_id> to update a product with its _id as <product_id>. Here, we are updating the name Updated Product, description Avg Product, and price 20. The server will then return the updated product as a JSON object.

Delete a product:

Replace <product_id> with the actual ID of the product you want to delete.

This will send a DELETE request to the server at http://localhost:3000/products/<product_id> to delete a product with its _id as <product_id>. The server will then return the deleted product as a JSON object.

Delete all products:

This will send a DELETE request to the server at http://localhost:3000/products to delete all products. The server will then return the deleted product as a JSON object.

Find products by condition:

This API will find all products with a name that starts with Product. Replace the $regex and $options values with your desired search condition.

Note that you may need to modify the request data and URL based on your specific implementation of the routes in your Express.js application.

Conclusion

In this article, we learned about Performing CRUD in Mongodb with Expressjs. Let us recap the points we discussed throughout the article:

  • Performing CRUD operations in MongoDB with ExpressJS is a common requirement for building web applications.
  • In expressJS CRUD is an essential operation, which refers to the four basic operations of persistent storage: Create, Read, Update, and Delete.
  • It is necessary to establish a connection between your ExpressJS application and the MongoDB database.
  • Establishing a connection can be accomplished by employing a MongoDB driver, such as Mongoose, that works with Node.js. Once the connection is established, the Mongoose models can be utilized to create, read, update, and delete documents in the MongoDB collections.
  • To read a document, you can use the find() method to search for documents that match a specific query.
  • To read a particular document use the findOne() method to retrieve the first document that matches a query.
  • To update a document, you can use the update() method or the findByIdAndUpdate() method to update an existing document.
  • To delete a document, you can use the remove() method or the findByIdAndRemove() method to remove a document from the database.
  • Node.js is a widely used runtime environment that is open-source and operates on Chrome's V8 JavaScript engine.
  • To create a Node.js app, you need to Install Node.js on your machine, then Navigate to the project directory, then Initialize the project, then Install required modules such as ExpressJs, Mongoose.
  • To setup Express web server, you need to Create the server file, then Define your server routes, then Start the server.
  • Then we configured the MongoDB database & Mongoose.
  • Then we have Defined Mongoose, and also the Mongoose Model.
  • Then we created a controller and implemented the CRUD functionality.
  • Then we created a router, and at last, we have run our NodeJs server with the command node server.js, and tested all the APIs.