CURD operations in node.

Image by StartupStockPhotos from Pixabay

Setup Node On System  

  • If you dont have node installed on your system then you can download it  click here
  • After installing the node on system.Open cmd and type node-v.It will give node version like this


      

Setup MongoDB On System


  •  If you dont have mongodb installed on your system then you can download it from here 
  •  Follow the installation instruction given there. 


Now setup our node project 


  • Open cmd type mkdir and give directory name.
  • Now your directory to that using cd directory name which we created. 
  • Now type npm init -y. this will make a package.json file in your folder.
  • Now we will npm  install package which we will use in our project.And all these will be shown in package.json.
  • The npm packages we will install here are express,mongoose,body-parser,ejs.

     
 

 This is how package.json looks     
      


  A little info about packages we using


  • body-parser will contain the data which will be sent from the form 
  • ejs it is used for viewing page in node.there are other view engines which you can use jade,handlebars etc. 
  • express is the framework on which all project is constructed.There are more frameworks available like hapi,sails,etc.
  • mongoose is used from connecting to mongodb from mainupulating data.

 Now setup files like as follows


  • make models ,views folder.
  • the node_modules,package_lock.json will automatically be made when you install packages.
        




 Models

  • The models folder will contain a file curd.js.Which will contain the table schema and all the function for manipulating data. like this
  •  in mongoose.Schema({}).we give the structure of our collection(table).
  • mongoose.model().we provide the table name for the collection(table) and the structure of the table.in the above code we are creating a curd collection(table).
  • now we will export it using module.export.The module.export is necessary because if make the file code accessable to other files.
  • now we passing it reference to curds so the we can do curd operation on data.
  • find(),update(),delete(),save() the are inuilt function in mongo for manipulating data.

 app.js

const express       = require('express');

const mongoose      = require('mongoose');

const bodyParser    = require('body-parser')

const curd          = require('./models/curd');

const app = express();

mongoose.connect('mongodb://localhost:27017/curd').then(()=>console.log('connected'))

.catch(()=>console.log('some error occured'))


//setting up view engine //

app.set('view engine','ejs');


// For getting data from form //

app.use(bodyParser.urlencoded({extended:true}))


// will load home page by default  //

app.get('/',(req,res)=>{

    curd.readata((err,data)=>{

        if(err){console.log(err)}

       else if(!data){

            res.render('home',{ad:{}})

        }

        else{

            console.log(data)

            res.render('home',{ad:data})

        }

    })

})


// Add Name //

app.post('/add',(req,res)=>{

    try {

        console.log(req.body)

       var addata = new  curd({

          name:req.body.uname 

       }) 

       curd.add(addata,(err,adata)=>{

          if(err){

              console.log('error',err)

          }

          console.log(adata)

             res.redirect('/')

         })

       } catch (error) {

         console.log(error)

    }

})


//Edit Name //

app.get('/edit/:data',(req,res)=>{

    try {

        curd.getbyid(req.params.data,(err,data)=>{

            if(err){console.log(err)}

            console.log(data)

            res.render('edit',{ad:data})

        })

    } catch (error) { 

         console.log(error)

    }

})


//Update Name//

app.post('/edit',(req,res)=>{

    try {

        const crd = {

            name : req.body.uname,

            id:req.body.id

        }

         curd.updatedata(crd,req.body.id,(err,data)=>{

              if(err){console.log(err)}

              console.log('edit',data)

              res.redirect('/')

         })   

    } catch (error) {

        console.log(error)

    }

})


//Delete Name//

app.get('/delete/:id',(req,res)=>{

    try {

        console.log(req.params.id)

       curd.deldata(req.params.id,(err,data)=>{

           if(err){

               console.log(err)

           }

           console.log(data)

           res.redirect('/');

       })  

    } catch (error) {

        console.log(error)

    }

})


//Setting Port //

const port = process.env.PORT || 3000;


// return server instance //

app.listen(port,()=>console.log('server running'+port))


module.exports=app;



  • here we import package mongoose,body-parser,express using require() function.
  • we also im port the models which made for data manipulation in models folder in curd.js file.
  • for making connection with database we using mongoose.connect() function.in this we have to provide localhost with the mongodb default port on localhost followed by the db name.the moongoose.connect() return promises to us.
  • we calling express() function and it will return a object to us.by that we can use the other function of express.
  • we use app.set() to setting up the template engine which we are using in prject.here we set it to ejs as we using ejs.
  • app.use() is a middleware which check all the request and response of the application.it get called everytime when the request comes and goes.we using bodyparser in it because bodyparser will get form data from the request which comes
  • process.env.PORT will automatically get the port number of the serve when we host it on server.
  • in res.render() we are provide the page name to be rendered and also sending data with it.

     
     Views 

  •  this will contain 2 ejs files. home and edit
  •  refer following to understand ejs https://ejs.co/. used here.

    home.ejs will contain following code





   edit.ejs will contain following code 

 
    

Comments

Post a Comment

Popular posts from this blog

Upload And Download File In Node

How To Use Sequelize-Cli In Node

Setup Flask Project