CRUD application with Node, Express,ejs and MongoDB | REST API in Node js

Deal Score+1
Deal Score+1

Finally i learned node js ,express js and mongodb for app development. I just want to share knowledge that i have get  during my experience

Crud application using node express,mongodb.

If some don’t work with mongodb node js or any server-side language then its will be very difficult to work with these language so first of all we will learn what is server-site language  why we use and what is node express and mongodb

  • Node js  

Node js  is server-side programming language that are use to develop server site application .

  •  Express js

Express js framework of node js its use for routing like GET,POST,PUT and delete. We can use any other framework but in this tutorial We will use Express js.

  •    Mongodb

Mongodb is database .its place where we store our application data.

  • Ejs

Ejs templating engine that are use for page render. We can use even other but in this example we will use ejs because its easy for new programmer.

What is CRUD mean.

C stand for Create mean we are inserting data in application.

R stand for Reading data from database .
U stand for Updating data from database.

D stand for Deleting data from database.

Prerequisites

Node js ,mongodb should be install in your computer if you don’t install Node js please just go node js website .

Mongodb the next requirement is Mongodb still if you don’t install please download here 

to check that node install just Run this command in cmd

Run this command :Node -v

if node install then it will show like that .

CRUD application with Node, Express,ejs and MongoDB | REST API in Node js

So if you have install node ,mongodb  then Let get started.

first of all install package.json    just run this in cms : npm init -y

if package.json is install then it will show like that.that. After  package.json  install then install theses dependencies

npm install express mongodb ejs 

CRUD application with Node, Express,ejs and MongoDB | REST API in Node js

first of all we will make directory like that in showing images

 

CRUD application with Node, Express,ejs and MongoDB | REST API in Node js

first create app.js file in main directory

const express=require('express');  
const mongoose=require('mongoose');
const ejs =require('ejs');
const app=express()
app.use(express.urlencoded({extended:true}))
app.use(express.static('public'));
app.set('view engine','ejs');
mongoose.connect('mongodb://localhost:27017/blog',
 {useNewUrlParser: true, useUnifiedTopology: true},()=>{
     console.log("connected to mongodb")
 });
app.listen(3000,function(req,res){
    console.log("server is runing on port 3000")
})

first of all we have require express, mongodb and ejs then we have create instant of express  App then have created

mongodb connection(mongodb://localhost:27017/blog) .We have created database (blog).

then we have created port 300 for server runing.

Next we have to create file  in router=>index.js

index.js

const router=require('express').Router()
const Blog =require('../models/Blog');
//router method for api
router.get('/',async(req,res)=>{
    const allBlogs=await Blog.find()
    res.render('index',{blogs:allBlogs})
})
//export file 
module.exports=router

after creating index.js router we have to create index.js file so lets create this file its home page of our application

index.ejs

 

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<!-- navigation bar code -->


<nav class="navbar navbar-expand-lg navbar-light bg-dark">
    <a class="navbar-brand" href="/">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>

        </ul>

    </div>
</nav>
<!-- end   nav -->
<div class="contianer">
    <h1>all blog post</h1>
    <% blogs.forEach(blog=>{%>
    <div class="card">
    
        <div class="card-body">
            <p class="text-muted">publish at:<%= blog.postedAt %> </p>
            <h5 class="card-title"><%= blog.title %> </h5>
            <p class="card-text"><%= blog.content.slice(0,200) %> </p>
            <a href="/blog/<%= blog._id %> " class="btn btn-primary">read more</a>
            <a href="/delete/<%= blog._id %> " class="btn btn-danger">Delete</a>
            <a href=" /edit/<%= blog._id %>" class="btn btn-warning">Edit</a>
            <a href=" /compose" class="btn btn-warning">create new post</a>
        </div>
    </div>
  <%  }) %> 
</div>

this is ejs main home page  file that show all post that we have create so lets create file that insert data into database.

compose.js

const express=require('express');
const Blog = require('../models/Blog');
const router=require('express').Router()

router.get('/compose',(req,res)=>{
    res.render('composeBlog')

})

router.post("/compose",(req,res)=>{
    const {title,content}=req.body
    if(!title || !content){
        return res.send("please enter all field");
    }
    console.log(title,content)

    const newblog=new Blog({
        title,content
    })
    newblog.save()
    .then(()=>{
        console.log("new post save succesfullty")
        res.redirect('/')
    })
    
})
module.exports=router

first of all  we have create  res.render(‘composeBlog’) routes that show the page where we have to insert our data

so let create composeBlog.ejs file

composeBlog.ejs

<!-- navigation bar code -->

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-light bg-dark">
    <a class="navbar-brand" href="/">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>

        </ul>

    </div>
</nav>
<!-- end   nav -->

<div class="constainer m-5">
    <h3 class="my-3">compose your blog here...</h3>
    <form action="/compose" method="POST">
        <input type="text" name="title" placeholder="enter the title" class=" form-control" required>
        <textarea placeholder="Enter the content here" name="content" id="" cols="30" rows="10"
            class="text form-control mt-3" required></textarea>
        <input type="submit" value="compose" class="button btn btn-sm btn-danger mt-4">

    </form>
</div>

Let also create mongodb file schema file your blog post

Create folder as above show in image models=>Blog.js and export its

const mongoose=require('mongoose');
const BlogSchema=new mongoose.Schema({


    title:{
        type:String,
        required:true
    },
    content:{
        type:String,
        required:true
    },
    postedAt:{
        type:String,
        default:new Date().toString()
    }
})
module.exports=new mongoose.model("Blog",BlogSchema)

after require the Schema lets run out app go to your favorite browser  localhost:3000/compose then its will show this screen .

lets insert some dumy data in your blog to see result after insert data in file go to home page localhost:3000 its will show you same post that you have created.

const express=require('express');
const mongoose=require('mongoose');
const ejs =require('ejs');
const app=express()
app.use(express.urlencoded({extended:true}))
app.use(express.static('public'));
app.set('view engine','ejs');
mongoose.connect('mongodb://localhost:27017/blog',
 {useNewUrlParser: true, useUnifiedTopology: true},()=>{
     console.log("connected to mongodb")
 });
 app.use(require('./routes/index'))
app.use(require('./routes/compose'))
app.use(require('./routes/blog'))
app.listen(3000,function(req,res){
    console.log("server is runging on port 3000")
})
//

Require all routes that you have created in app.sj

Now we have done inserting and fetching data in our app let start work in deleting and updating part.

const router=require('express').Router()
 const Blog =require('../models/Blog')
router.get('/blog/:id',async(req,res)=>{
  const {id}=req.params

  const getBlog=await Blog.findOne({_id:id})
  res.render("particularBlog",{blog:getBlog})
})
router.get('/blog/:id',(req,res)=>{
      res.render('pre',{blog:getBlog})
})
router.get("/delete/:id",(req,res)=>{
     const {id}=req.params;
      Blog.deleteOne({_id:id})
      .then(()=>{
          console.log("Deleted post successfully");
          res.redirect('/')
      }).catch(err=>{
          console.log(err)
      })
})
  .get("/edit/:id", async (req, res) => {
    const { id } = req.params;

    const getData = await Blog.findOne({ _id: id });
    res.render("editBlog", { blog: getData });
  })

.post("/edit/:id", (req, res) => {
    const { id } = req.params;
    const { title, content } = req.body;

    Blog.updateOne({ _id: id }, { title, content })
      .then(() => {
        console.log("successfully! updated the blog!");
        res.redirect("/");
      })
      .catch((err) => console.log(err));
  });
module.exports=router;

 

lets also created edit part in ejs file

<!-- navigation bar code -->

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-light bg-dark">
    <a class="navbar-brand" href="/">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>

        </ul>

    </div>
</nav>
<!-- end   nav -->

<div class="constainer m-5">
    <h3 class="my-3">compose your blog here...</h3>
    <form action="/edit/<%= blog._id %> " method="POST">
        <input type="text" name="title" value="<%= blog.title %> " placeholder="enter the title" class=" form-control"
            required>
        <textarea placeholder="Enter the content here" name="content" cols="30" rows="10" class="text form-control mt-3"
            required><%= blog.content %></textarea>
        <input type="submit" value="save change" class="button btn btn-sm btn-danger mt-4">

    </form>
</div>

output of edit page

CRUD application with Node, Express,ejs and MongoDB | REST API in Node js

if we want to see a particular post in then have to create a particlarBlog.ejs

 

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-light bg-dark">
    <a class="navbar-brand" href="/">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="/compose">write </a>
            </li>

        </ul>

    </div>
</nav>
<!-- end   nav -->
<div class="container mt-5">
    <p><%= blog.postedAt %> </p>
    <h3><%= blog.title %> </h3>
    <p class="mt-5"><%= blog.content %> </p>
</div>

the final output of blog:

Thanks for reading blogs post hope you like this.

 

20 Comments
  1. Reply
    Fixed Table Headers using Only HTML and CSS
    March 25, 2021 at 5:15 pm

    […] Fixed Table Headers using Only HTML and CSS learn how to create crud app in node js […]

  2. Reply
    Show Error Messages Design in html CSS
    March 25, 2021 at 5:21 pm

    […] please check also our other post CRUD app in node js  […]

  3. Reply
    Form Validation in HTML5 – Show Error Messages on Click button
    March 25, 2021 at 5:42 pm

    […] CRUD application with Node, Express,ejs and MongoDB | REST API in Node js […]

  4. Reply
    Animated Tab Bar using html,css and javascript.
    March 26, 2021 at 5:22 am

    […] CRUD application with Node, Express,ejs and MongoDB | REST API in Node js […]

  5. You could certainly see your enthusiasm within the work you write. The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. Always follow your heart.

  6. I am not sure where you’re getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for wonderful info I was looking for this information for my mission.

  7. Reply
    Slyvia Devincenzi
    June 5, 2021 at 3:53 am

    You can definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  8. Hey there, I think your blog might be having browser compatibility issues. When I look at your website in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, superb blog!

  9. fantastic put up, very informative. I’m wondering why the opposite specialists of this sector do not understand this. You must continue your writing. I am sure, you’ve a great readers’ base already!

  10. Reply
    Kieth Penaherrera
    June 10, 2021 at 5:20 am

    It’s actually a nice and helpful piece of information. I’m glad that you shared this helpful information with us. Please stay us up to date like this. Thank you for sharing.

  11. Unquestionably believe that which you said. Your favorite justification appeared to be on the internet the simplest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they just do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks

  12. I do not know whether it’s just me or if perhaps everybody else encountering problems with
    your website. It seems like some of the text within your content are
    running off the screen. Can someone else please comment and let me
    know if this is happening to them as well? This might be a issue with my browser because
    I’ve had this happen before. Thank you

  13. Reply
    chó con poodle dễ thương
    August 22, 2021 at 5:22 am

    Thanks for the auspicious writeup. It in fact used to be a enjoyment account it. Look complex to far added agreeable from you! However, how could we be in contact?

Leave a Reply to Omer Giessler Cancel reply

Logo
Enable registration in settings - general