CRUD Operations with Express, Node, and MongoDB. Pt 2.

Oremei Akande
4 min readAug 21, 2020

--

Hi, it’s nice meeting you. Thanks for giving me the opportunity to share with you one or two things I learned while learning express, node, and MongoDB. Trust me I am still learning. So, why not join in the process.

This is the second part of this tutorial. You can find the first part here. There we saw how to set up a MongoDB on Atlas. Here, we will be looking at communicating with the database. By writing to, reading from, and updating the database. We will continue from where we stopped. First, let us create a database on the cluster we created.

You remember this image from the cluster we created? No? check here. Yes? Amazing! The difference here is that we won’t be clicking on the ‘CONNECT’ button but the ‘COLLECTIONS’ button. So go ahead and click on it.

You should see this screen(above). Click on ‘Add My Own Data’ and enter your database name. In my case, I entered ‘crud_mongo’ and ‘users’ as the collection name. Click on create and you should have this on your screen.

Next, go to your index.js file and add this connection to your express application.

If all went well you should see “Successfully connected to MongoDB Atlas!” on your terminal.

YAAS! we are finally connected.

Here comes the interesting part of this tutorial. Writing endpoints for the express application. Let’s the first endpoint for the base of the application on http://localhost:8085.

On your browser enter: http://localhost:8085. You should see:
Congrats! We just build your first express application.

Mongoose Schema for the notification app.

The fields we will be accepting, for now, are the subject, body, date_sent, recipient, and is_read. This is the schema below.

Create Notifications:

The mongoose schema will create a collection for notifications and we can use the mongoose.save() function to save data from our app to MongoDB Atlas.

So, we will test this endpoint with Talend and quickly create a notification for some users.

The request screenshot.

The response screenshot:

The response.

I will create other notifications so we can get all notifications.

Get Notifications (Read)

This endpoint will help us get all notifications in the database.

Response on talend:

The three notifications we have in the database.

Get notification by id:

This endpoint lets us get details for a single notification by Id. When we create records in MongoDB, MongoDB adds the _id field.

Response on talend:

Update Notifications:

Delete Notifications:

Response on talend:

--

--