MongoDB with NodeJS
MongoDB is a very popular document-oriented database in the NoSQL world. It makes use of collections and documents instead of tables and rows of Relational databases. A Collection consists of a set of documents. Data will be stored in a key-value pair in a document.
Here we are looking into how to integrate MongoDB with a NodeJS application and do basic CRUD operations with it. Let’s jump to the work without going into much more detail.
First, you need to set up MongoDB. In this implementation, MongoDB Atlas which is a cloud database has been used. If needed we can install MongoDB locally also.
You can find the details of setting up MongoDB Atlas here.
Setting up NodeJS project
- Create a folder on your computer and open the command inside it. Initialize the project with npm init -y command.
Following dependencies have been used in the NodeJS app.
express
mongoose
nodemon
dotenv
2. Install the above dependencies.
npm i express mongoose nodemon dotenv
3. Add the start script on package.json as below.
"scripts": {
"start": "nodemon app.js"
}
Project Structure
The folder structure of the project
Implementation
Connection with MongoDB is formed in db.js.
The connection string can be provided in .env and this is how it looks like.
DB_CONNECTION = mongodb+srv://<username>:<password>@cluster0.z4xzn.mongodb.net/<dbname>?retryWrites=true&w=majority
You can find this in MongoDB cloud.
This is how the app.js file looks.
Type nodemon app.js in the command prompt to start the project. If everything is ok you will see the logs “connected” (If database connected successfully) and “Listening on port 3000”. Then you are good to go.
First, We need to create Schemas for the application. The following has been created to save customer details. It is in customer_model.js.
customerSchema is the parent schema and ordersSchema is a child schema. Because the order is an object that contains the details of the order.
Now we can perform database operations via the app. To test the endpoints I used Postman. All endpoints are defined in customer_routes.js. Let’s jump into the CRUD operations.
Save Data
To save data into the database, we can do the following.
Let’s test this API with Postman.
We got the response as above. Now let’s check the database.
It is working!. Data has been saved in the mongo cloud database. We can add data as much as we need. I have added another object like this.
{
"name": "Anna Faris",
"email":"annafaris@y.com",
"order": {
"orderId": ["ord002", "ord003"],
"title": ["OnePlus 9RT", "Realme Bluetooth Speaker"],
"price": ["$1065","$40"]
}
}
And here is the database now.
Read data
Now let’s try to retrieve all records from the database. Code looks following.
And here is the response by postman.
We can also retrieve a specific object we need. For example, here I’m fetching the record for Anna by id.
The code looks like follows.
And here is the result.
Update data
This is how we can update a document in the database.
Here I’m trying to update the email, Anna Faris, from annafaris@y.com to annafaris@z.com. Since it is an update I have used PATCH in Postman.
Let’s check the database to check whether it is updated or not.
As we can see the email address of ‘Anna Faris’ has been changed to annafaris@z.com.
Now let’s go into the delete operation.
Delete data
TO delete data we can write a code snippet like follows.
I have added another record as James Anderson. Let’s try to delete it.
And this will be a DELETE operation in Postman. Delete is going to happen by id.
We got the response as expected. And database does not have a record for James Anderson anymore.
Likewise, we can perform any CRUD operation.
Github Link: GitHub — Kanchana46/NodeWithMongoDB
Hope you find this helpful. Happy coding!