In this blog, we are going to make a CRUD operation using node js and MongoDB.
CRUD stands for Create(insert data to database), Read(Retrieve a data from database), Update(Edit from database), and Delete(delete a data from database)
At least NPM version >= 5.6
Basic knowledge about node js
Note: I’m using windows 10 20H2. And the editor is VS Code editor.
First of all we need to create a folder. You can create it manually. I will use my terminal. So open your terminal then run this command :
Now my file name is server.js so I’m going to start here:
Add these codes to your server .js file :
So in this picture, you have a question that what the hell requires doing here. Require is like import. Express js documentation follows the old method of import. Hopefully, it will be updated soon.
So now I tell you the main steps:
First Import the express like above the picture.
Then convention is to use the express into a variable and call it like a function. And my app variable is the express function now.
Then the main is your port I use here the environment variable Cause when I deploy it to the server it uses the environment variable. And local machine Our port is 5000. You can give it any number you like.
Then We see the CORS. CORS mainly stands for Cross-origin resource sharing. It allows you to make requests from one website to another website in the browser, which is normally prohibited by another browser policy called the Same-Origin Policy (SOP).
Then I uses the dotenv library for environment variable.
Now I know you ask me a question what is middleware. Middleware is like a middle man who works from the middle. Here we use two middleware one is cors() and the second one is express.json(). So the first middleware cors **is for cross-origin policy and the **express.json() is for parsing it to JSON format.
You can find these codes in your own MongoDB database. Just go there and click on connect option they will provide you with the above code. Note: You can see the uri on the picture I use environment variables for security purposes. I hide my database username and password using the template literals.
Create-operation: In the picture, I used the async/await. You can use then. First of all, we need to connect the database so that is why I used client. connect(). Then create a database variable for your db and name it in your way. Then we need a collection so create a collection. I create two collections. Named order collection and foodcollection. Now In my picture you can see line number 14 I insert a document into the database. In the app.post function you can see I use the instertOne method which is provided by mongodb. For insert data or create data in MongoDB.
You can follow the screenshot for all the operations or check here for more details: MongoDB Docs