Wednesday, 25 October 2023

NodeJS and MongoDB step by step Example

We can see below example step by step:

We will add Project and Enquiry details in MongoDB and show Enquiry details based on Project as below:


--Open VS Code from folder "ABCBuilderAPI"

Below is the folder structure:

>Open New Terminal & Execute below command

>npm i express mongoose cors --save

>npm i nodemon --save

>npm i mongoose@6.9.2 -----this is working version

>npm i mongoose@7.0.0 -----this version giving Mongoose Callback error


I. Add code in index.js

Code Snippet:-

const express=require('express');

const app=express();
const corsOption={
    origin:"http://localhost:3000",
    optionSuccessStatus:200,
    methods:"GET,PUT"
}
const cors=require('cors');
const api=require("./RestAPI/api");

app.use(express.json());
app.use(express.urlencoded());
app.use(cors());
app.use(cors(corsOption));

app.get("/",(req,res)=>{
    res.send("API Example");
})

app.use("/",api);
app.listen(5000,function(){
    console.log('Nodemon server started..!');
})

II. Add code in package.json for listening server path

Code Snippet:-


III. Add folder ConnectDB>>MongoConnect.js and add code for connect DB

Code Snippet:-

var mongoose=require('mongoose');
mongoose.set('strictQuery',true);
//mongoose.connect("mongodb://localhost:27017/ABCBuilders",{useNewUrlParser:true});
mongoose.connect("mongodb://127.0.0.1:27017/ABCBuilders",{useNewUrlParser:true});
var conn1=mongoose.connection;
conn1.on("connected",function(){
    console.log('Connected to MongoDB Database.');
})
conn1.on("disconnected",function(){
    console.log('Disconnected from MongoDB Database.');
})
conn1.on("error",console.error.bind(console,"Connection error."));
module.exports=conn1;

IV. Add folder Models>>ProjectInfoModel.js and add code to sync table model properties

Code Snippet:-

const mongoose=require('mongoose');
let projSchema=mongoose.Schema({
    ProjID:
    {
        type:Number,
        require:true
    },
    ProjName:
    {
        type:String,
        require:true
    },
    ProjType:
    {
        type:String,
        require:true
    },
},{collection:'ProjectInfo'});
let ProjectInfo=module.exports=mongoose.model('ProjectInfo',projSchema);

V. Add folder Models>>EnquiryInfoModel.js and add code to sync table model properties

Code Snippet:-
const mongoose=require('mongoose');
let enquirySchema=mongoose.Schema({
    EnquiryId:
    {
        type:Number,
        require:true
    },
    Name:
    {
        type:String,
        require:true
    },
    MobileNo:
    {
        type:Number,
        require:true
    },
    EmailID:
    {
        type:String,
        require:true
    },
    ProjID:
    {
        type:Number,
        require:true
    },
},{collection:'EnquiryInfo'});
let EnquiryInfo=module.exports=mongoose.model('EnquiryInfo',enquirySchema);

VI. Add API service code in api.js file

Code Snippet:-

const express=require('express');
const router=express.Router(); //Navigate through different api methods
const ProjectInfo=require('../Models/ProjectInfoModel');
const EnquiryInfo=require('../Models/EnquiryInfoModel');
const conn1=require('../ConnectDB/MongoConnect');

router.get("/AllProject", function(req,res){
    let Project=ProjectInfo.find({},function(err,project){
        if(err)
        console.log(err);
        else
          res.json(project);
    })
})

router.get("/ProjectByID/:id", function(req,res){
    let pid=req.params.id;
    let data=ProjectInfo.find({"ProjID":pid},function(err,result){
        if(err)
        console.log(err);
        else
          res.json(result);
    })
})

router.get("/EnquiryByPID/:id", function(req,res){
    let pid=req.params.id;
    let data=EnquiryInfo.find({"ProjID":pid},function(err,result){
        if(err)
        console.log(err);
        else
          res.json(result);
    })
})

//insert to the Project
router.post("/NewProject",(req,res)=>{
    const proj=new ProjectInfo(req.body);
    proj.save().then((p)=>{
        res.status(201).send(p);
    }).catch((error)=>{
        res.status(400).send(error);
    })
  });

//insert to the Enquiry
router.post("/NewEnquiry",(req,res)=>{
    const enquiry=new EnquiryInfo(req.body);
    enquiry.save().then((e)=>{
        res.status(201).send(e);
    }).catch((error)=>{
        res.status(400).send(error);
    })
  });

module.exports=router;

>npm start 


To Set up MongoDB: 

--MongoDB Shell download: https://www.mongodb.com/try/download/shell --Running from Client: >cd C:\Users\subas.patel\Documents\Subas\Softwares\mongosh-1.6.2-win32-x64\mongosh-1.6.2-win32-x64\bin>mongosh --Running from Server: >C:\Program Files\MongoDB\Server\6.0\bin>mongod

> use ABCBuilders
> db.ProjectInfo.find()
> db.ProjectInfo.insertOne({"ProjID":200,"ProjName":"Prestige Construction","ProjType":"On Going"})
> db.ProjectInfo.insertOne({"ProjID":201,"ProjName":"My Home Construction","ProjType":"Ready to Build"})

> db.EnquiryInfo.find()
>db.EnquiryInfo.insertOne({"EnquiryId":1,"Name":"Ramnath","MobileNo":2312424290,"EmailID":"ram@gmail.com","ProjID":200});
>db.EnquiryInfo.insertOne({"EnquiryId":2,"Name":"Ram","MobileNo":3312424290,"EmailID":"r@gmail.com","ProjID":201});

To Be continued.. to consume above Node API using ReactJS in next post..

No comments:

Post a Comment