onsdag 24. februar 2016

Node.js, Express and Mongodb beginner tutorial; make a simple comment site. | Part 3: Register and show comments

This is a continuation of a tutorial. If you have not finished step 1 and 2, do that first: http://allrounddeveloper.blogspot.no/2016/02/nodejs-express-and-mongodb-beginner.html


Step 5 – Setup for comments

The final part is to make the users able to comment. For this too, I start with the jade file, but this one is a bit more complicated. This is the comments.jade file:


doctype html
html
    head
        title Comments
        meta(charset="utf-8")
        link(rel="stylesheet",href="stylesheets/style.css")
    body
        h1 Comments
        each comment, i in comments
            table
                tr
                    th=comment.username
                    th=comment.date
                tr
                    td(colspan="2")=comment.comment
        if loggedin
            h2 Comment in the field below.
            form(method="post",action="/submit")
                textarea(name="comment")
                br
                input(type="submit",value="Submit comment")
        else
            p You have to be logged in to comment.
            br
            a(href="/login") Log in.
            br
            a(href="/signup") Sign up.
 


We can send arrays or variables with information to the jade file. In this case, we send the comments array into the jade engine.


The jade file says that for every comment in the array, the jade engine would fill in the username, date and content of the comment. "For each" is for doing something with every instance in an array. We use an equals sign to set the content of an HTML-tag to a variable.


We also use an if-statement, which means that if the bool is true the jade engine outputs the tags that is nested beneath. We have an else statement with some other content. We send a bool that tells jade engine whether the user is logged in.


We need node.js to send the comments to the jade engine, when the user is on the front page.


app.get("/",function(req, res) {

    MongoClient.connect("mongodb://localhost:27017/admin",function (err, db) {

        if (err) {

            console.log('Unable to connect to the mongoDB server. Error:'+ err);


        else {

            console.log('Connection established to mongodb://localhost:27017/admin');

            var users=db.collection("users");

            var comments=db.collection("comments"); 

//new collection where we store the comments

            var loggedin;

//a variable that checks whether the user is logged in

            if (req.cookies.session_id==""){ 

//if the user has no session_id cookie, the user is not logged in. req.cookies.cookie_name finds the value for a given cookie from the user.

                loggedin=false;

            }

            else{

                users.findOne({"session_id": to_hash("Another random salt"+req.cookies.session_id+"Randomed hash")},function(e,docs){ 


//check if an user actually has the hash value from the session_id

                    if(e) throw e;

                    if (docs==null){

                        loggedin=false;

                    }

                    else{

                        loggedin=true;

                    }

                });

            }

            comments.find({}).sort({"date":-1}).toArray(function(e,com){ 

//comments.find finds all the comments in the database. The sort command says that mongodb shall sort the comments in a descending order, from newest to oldest. ToArray function makes the result to a function, stored in the variable “com”.

                res.render("comments",{ 

//this is the way we send variables to the jade engine. “comments” in the jade file is given the variable “com” from node.js.

                "comments":com,

                "loggedin":loggedin

                });

                db.close();

            });
        }
    });
});


The only thing left now is to register the comments that is sent. I sent the post requests to “/submit”.


Here is the node.js code:


app.post("/submit",function(req, res) {

    if (req.body.comment==""){

        req.send("Sorry, you cannot have an empty comment.");

    }

    else if (req.cookies.session_id==""){

        res.send("You have to be logged in to comment.");

    }

    else{

        MongoClient.connect("mongodb://localhost:27017/admin", function (err, db) {

            if (err) {

                console.log('Unable to connect to the mongoDB server. Error:'+ err);

            }
            else {

                console.log('Connection established to mongodb://localhost:27017/admin');

                var users=db.collection("users");

                var comments=db.collection("comments");

                users.findOne({"session_id": to_hash("Another random salt"+req.cookies.session_id+"Randomed hash")},function(e,docs){

                    if(e) throw e;

                    if (docs==null){

//if no user is found with the cookie, the login is not valid.

                        res.send("Your login is not valid.");

                        db.close();

                    }

                    else{

                        comments.insert({"comment":req.body.comment,"username":docs.username,"date":new Date()},function(err,result){

//the date variable saves the date when the comment is submitted.

                            if (err) throw err;

                            res.send("Comment saved.");

                            db.close();

                        });
                    }
                });
            }
        });
    }  
});


All my project files can be found here: https://www.dropbox.com/sh/vaqnof1ebejb31j/AABGmy_AQPS3IIaWLo7PEAoSa?dl=0


If there are any questions or suggestions of things I could have done better, please use comment section below.


Ingen kommentarer:

Legg inn en kommentar