MongoDB — CRUD Operations

Irit Kushwaha
GDSC UMIT
Published in
2 min readJan 31, 2022

One of the broadly common operations we’ll perform when working with MongoDB is querying document data.

The more favorable you understand how to procure data, the more effectively you can access the information you need when you require it.

Querying data is part of a wider set of operations commonly referred to as CRUD (Create, Read, Update, and Delete).

  • When you insert data into a MongoDB database, you create the data.
  • When you query data in the database, you read the data.
  • When you modify data, you update the data
  • When you remove data, you delete the data.

Let us now discuss create, read, update and delete operations or CRUD operations in MongoDB.

Step 1 — Setting up the project

Create a new directory for your project

mkdir mongoDB_crud

Navigate to the directory:

cd mongoDB_crud

Now initialize a new npm project

npm init -y

Next, install express and mongoose:

npm install express@4.17.1 mongoose@5.12.13

Step 2 — Setting up the index.js

In index.js we will run the Express server and connect to the MongoDB Atlas

Step 3 — Schema

Schemas allow you to decide exactly what data you want and what options you want the data to have as an object.

Step 4 — Create Route

Create a new directory controller. Inside this directory create new directory routes.

Next, we will build the functionality to create a new task item and save it to the database.

Step 5 — Read Route

Now we will start by reading all tasks in the database.

Revisit the routes.js file and add the following code

Step 6 — Update Route

Next, we will build the functionality to update an existing task item and save the changes to the database.

Revisit the routes.js file and add the following code

Step 7 — Delete Route

Finally, we will build the functionality to remove an existing food item and save the changes to the database.

Revisit the routes.js file and add the following code

If you want to git clone the code and play with it yourself, here’s the link to my GitHub Repo! Repository Link 🔗

If you have any questions about this tutorial, please let me know in the comments section of this blog post. You can also contact me through Linkedin. I’m happy to assist you 😊!

--

--