CRUD website with MongoDB

Hello Developers I hope you are doing amazing. Here I am with my first blog on hashnode which will explain CRUD applications using MongoDB database. I will make sure that you will have complete idea of MongoDB at the end of this blog.

You can always refer official documentation but this blog will help you connect the database with your express server, creating a schema and doing all the database operations.

Connecting server to the database

Advantage of using MongoDB is that it is database which use cloud platform to save data so that we don't have any problem using database after deployment otherwise we can't deploy our website without a driver if database is in one computer. Cloud Database is called MongoDB atlas, we create cluster and then collections in it.

For connecting to database you can refer to this video , we will not go in depth of that part because it's very linear and simple.

Creating Schema

Now we have to create a schema of all the attributes that are gonna be there in database of our project and create a new user that will point to that schema. For example if we create hotel booking page then schema in JS will look like

image.png

Now we have create a Database and Schema we will do the operations with database

Create

In hotel booking form whenever submit button will be triggered we will grab the values of input tags at the instant and save into the database. New user will be created in database with the values extracted from the form and query used is username.save()

image.png

Delete

If we follow our example, now user wants to cancel booking so now we have to delete that from database. For deletion process we need one attribute on basis of which we can process like delete from database where name is "john doe" so booking under name of john doe and all the attributed from db will be deleted.

image.png

Here we can see we are using query user.deleteOne({ BookingId : req.body.bookingID}) i.e delete one query where booking id is given. BookingID is attribute name and req.body.bookingID will get the ID from user of which data is being deleted.

Read

If user wants to check his hotel booking details then he will use My bookings page where he can see his bookings on hotel site for which we will use read operations. Example : We want to see booking under name of "john smith" in collection hoteluser, then we will use query hoteluser.find({name : "john smith"}). That will show all data which have name john smith.

If we want to save while object in array then we will use hoteluser.find({ name : "john smith" }).toArray

I hope you have got the clear idea about how MongoDB works will ExpressJS, nodeJS and HTML. For more detailed information you can checkout their official documentation.

Thank you for reading. Happy coding !!