MongoDB CURD

1. Create a new Node.js project:

npm init -y  //Initialise and Configure Our Project
npm i express mongoose morgan dotenv cors --save
// express install
// mongoose: mongodb install
// morgan: for show log
//cors: cors install
npm i -D nodemon //server restart when some change

2. Edit package.json

"name": "blog_mongodb",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
...

When I will write the following command ‘’npm start’’ than ‘’npm nodemon app.js’’ will be run.

3. Project Structure:

4. app.js


module.exports = app;

5. server.js

const app = require("./app");
const port = process.env.PORT || 4545;

// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});

6. Create Mongoose Model:

model
-HomeModel

//New Schema toiri kori
const userSchema = new Schema({
title:{
type: String,
required: true,
index: true,
trim: true
},
description: {
type: String,
required: true,
trim: true
}
}, { timestamps: true })
const user_table = model('user_table',userSchema); //create user_table
module.exports = user_table

7. Create Controller:

controllers
-HomeController

CRUD Operation:

8. Start

Create:

/api/app/v1/blog/create

Get All:

/api/app/v1/blog

Get Blog By ID:

/api/app/v1/blog/getSingleBlog/62fa1030536d34e59853276a

Update:

/api/app/v1/blog/update/62fa1030536d34e59853276a

Delete:

/api/app/v1/blog/delete/62fa1030536d34e59853276a

Details:

--

--

Senior Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store