RESTfull routes on Node.js and MongoDB

REST stands for representational state transfer which basically provides a way of mapping HTTP verbs such as (GET, POST, PUT, DELETE) with CRUD actions such as (CREATE, READ, UPDATE, DELETE). Whenever we click on a link on the webpage we are basically making a state transfer from one page to another. For example, when we click for the homepage of the blog website we want to get all the blogs that are stored on the server’s database which is basically a mapping of HTTP GET request with the READ request of database.

Similarly, there are more HTTP requests where we are interacting with the database like creating a blog, editing a blog, deleting a blog, and much more. RESTfull routes are standard conventions of how to implement these mapping. It’s not necessary that you can’t implement such functionality without RESTfull routes but these are the simplest and standard route which are followed by most of the developer. We are going to understand how they work by creating a simple blog application where we can delete, add, create, edit, and display the blog.

Functionality Path HTTP Expected Output
Index /blogs GET List all blog posts
New /blogs/new GET Show a form to get blog info
Create /blogs POST Add blog to database and redirect to home page
Show /blogs/:id GET Show a blog having given id
Edit /blogs/:id/edit GET Show edit form for a blog
Update /blogs/:id PUT Update a particular blog and redirect to updated blog
Destroy /blogs/:id DELETE Delete a particular blog and redirect to home page

We are going to use node.js which will serve the webpage and MongoDB for storing the data. The entire code is available at Github which includes how to interact with the database and configure all dependency. Just to give little idea about the data schema below is Schema for our blog post.

Note: Entire code is available at Github

filter_none

edit
close

play_arrow

link
brightness_4
code

var blogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {type: Date, default: Date.now}
});
  
var Blog = mongoose.model("Blog", blogSchema);

chevron_right


Index Page(GET): For the index page, we want to display all the blogs which are stored in the database. To do so first we will get all data from the database using find() function of MongoDB and then send the result to a page that will show those posts. We are finding all the blog posts stored in the database which we are retrieving and handling using the function inside and if an error occurred we are sending to console ERROR! message and if everything works fine then we are rendering the index page where we are passing all blogs as data(blogs) which basically contain all blog info. Which is further used by the index page to display those data.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Routes
app.get("/blogs", function(req, res){
    Blog.find({}, function(err, blogs){
        if (err) {
            console.log("ERROR!");
        } else {
            res.render("index.ejs", {blogs: blogs});
        }
    });
});

chevron_right


Filename: index.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<% blogs.forEach(function(blog){ %>
    <img src="<%= blog.image %>">
    <a href="/blogs/<%= blog._id %>"><%= blog.title %></a>
    <%= blog.created.toDateString() %>...</span>
    <%- blog.body.substring(0, 50) %>
    <a href="/blogs/<%= blog._id %>">Read More</a>   
<% }) %>

chevron_right


New Blog(GET) and Create Blog(POST): We want to add a new blog so we need to get the form that will take input from the user. Hence first we will use new.ejs to render the form after that we will fill all the information and after that, we want to save it into the database which we will do by performing a POST request. Observe that, we have the same route as above but here only request type is changed which will be handled separately. We are creating a new blog post by using MongoDB create() function. If we don’t get any error, we will direct to the home page where the user can see that blog has been added and confirms that operation executes successfully.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Render the new.ejs page that contains
// the form for adding a blog
app.get("/blogs/new", function (req, res) {
    res.render("new.ejs");
});
  
// Add data to database and redirect to
// home page where we see the new page
// with updation
app.post("/blogs", function (req, res) {
    Blog.create(req.body.blog, function (err, newBlog) {
        if (err) {
            console.log("ERROR!");
        } else {
            res.redirect("/blogs");
        }
    });
});

chevron_right


Filename: new.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<form action="/blogs" method="POST">
    <label>Title</label>
    <input type="text" name="blog[title]"
                placeholder="Title">
    <label>Image</label>
    <input type="text" name="blog[image]" 
                placeholder="Image">
    <label>Blog Content</label>
    <textarea name="blog[body]"></textarea>
    <input type="submit">
</form>

chevron_right


Show(GET): Generally, the blog home page doesn’t show all blogs entirely it only shows starting few lines and if a user wants to read it based on its title and preview, we want to direct to a new page where the entire blog is shown in our case we will redirect to show.ejs HTML file. To do so all the blogs have unique id associated with it and if we want to display a particular blog, we will simply get the id of that blog and use findById() to get data and send it to show.ejs HTML file where data will be shown.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Routes
app.get("/blogs/:id", function(req, res){
    Blog.findById(req.params.id, 
        function(err, foundBlog){
        if (err) {
            console.log("ERROR!");
        } else {
            res.render("show.ejs"
                {blog: foundBlog});
        }
    });
});

chevron_right


Filename: show.ejs

filter_none

edit
close

play_arrow

link
brightness_4
code

<%= blog.title %>
<img c src=" <%= blog.image %>">
<span><%= blog.created.toDateString() %></span>
<p><%- blog.body %></p>
<a href="/blogs/<%= blog._id %>/edit">Edit</a>
<form action="/blogs/<%= blog._id %>?_method=DELETE"
            method="POST">
    <button class="ui red inverted button">
        Delete
    </button>
</form>

chevron_right


Edit(GET) and UPDATE(PUT): Sometimes we want to edit a blog, we first need a unique id of the blog after that sent user to a different page where a form is shown which is prefilled with the previous data and the user will update its data after that user will send to updated blog. To do so first get a request to go edit.ejs page then we will use PUT request which will use the findByIdAndUpdate() function of MongoDB to update the data with data that was already in the database under given id.

filter_none

edit
close

play_arrow

link
brightness_4
code

app.get("/blogs/:id/edit", function(req, res){
    Blog.findById(req.params.id, function(err, foundBlog){
        if (err){
            console.log("ERROR!");
        } else {
            res.render("edit.ejs", {blog: foundBlog});
        }
    });
});
  
app.put("/blogs/:id", function(req, res){
   Blog.findByIdAndUpdate(req.params.id, 
    req.body.blog, function(err,updatedBlog){
       if (err) {
           console.log("ERROR!");
       } else {
           res.redirect("/blogs/"+req.params.id);
       }
   });
});

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

Edit <%= blog.title %>
<form action=
    "/blogs/<%= blog._id %>?_method=PUT"
    method="POST">
    <label>Title</label>
    <input type="text" name="blog[title]" 
            value="<%= blog.title %>">
    <label>Image</label>
    <input type="text" name="blog[image]" 
            value="<%= blog.image%>">
    <label>Blog Content</label>
      
    <textarea name="blog[body]">
        <%= blog.body%>
    </textarea>
    <input type="submit">
</form>

chevron_right


Destroy(DELETE): Lastly, if we want to delete a specific blog, we will simply use the ID of the blog and use the findByIdAndRemove() function of MongoDB to delete a specific blog from the database.

filter_none

edit
close

play_arrow

link
brightness_4
code

app.delete("/blogs/:id", function(req, res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if (err) {
            res.redirect("/blogs");
        } else {
            res.redirect("/blogs");
        }
    });
});

chevron_right





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.