Home Mongo DB Solution The solution Homework 3.3 M101JS: MongoDB for Node.js Developers

The solution Homework 3.3 M101JS: MongoDB for Node.js Developers

The solution homework 3.3 M101JS: MongoDB for Node.js Developers

Making your blog accept comments

In this homework, you will add code to your blog so that it accepts comments. Download and unpack the files for this homework from the Download Handout link. You will be using the same code as you downloaded for homework 3.2, along with the changes you made.

We have removed parts of the code that uses the Node.js driver to query MongoDB from posts.js and marked the area where you need to work for HW 3.3 with “hw3.3 TODO”.

In a terminal:

Linux/Mac:

cd blog/ 
grep -rn "hw3.3 TODO" *

Windows:

cd blog/ 
find /n "hw3.3 TODO" *

You should not need to touch any other code. The database call that you are going to add will add a new comment to a given post.

This assignment has fairly little code, but it’s a little more subtle than the previous assignment because you are going to be manipulating an array within the Mongo document. For the sake of clarity, here is a document out of the posts collection from a working project that also has comments.

{
"_id" : ObjectId("513d396da0ee6e58987bae74"),
"author" : "andrew",
"body" : "Representatives from the planet Mars announced today that the planet would adopt MongoDB as a planetary standard. Head Martian Flipblip said that MongoDB was the perfect tool to store the diversity of life that exists on Mars.",
"comments" : [
{
"author" : "Larry Ellison",
"body" : "While I am deeply disappointed that Mars won't be standardizing on a relational database, I understand their desire to adopt a more modern technology for the red planet.",
"email" : "larry@oracle.com"
},
{
"author" : "Salvatore Sanfilippo",
"body" : "This make no sense to me. Redis would have worked fine."
}
],
"date" : ISODate("2013-03-11T01:54:53.692Z"),
"permalink" : "martians_to_use_mongodb",
"tags" : [
"martians",
"seti",
"nosql",
"worlddomination"
],
"title" : "Martians to use MongoDB"
}

As a reminder, to run your blog, go into the blog directory and type:

npm install
node app.js

Note that you add comments in this blog from the blog post detail page, which appears at

http://localhost:8082/post/post_slug

where post_slug is the permalink. For the sake of eliminating doubt, the permalink for the example blog post above is

http://localhost:8082/post/martians_to_use_mongodb

Ok, now it’s time to validate you got it all working.

From the top of this page, there was one additional program that should have been downloaded:mongoProc.

With it, you can test your code and look at the Feedback section. When it says “user creation successful” and “user login successful”, you can Turn in your assignment.

Solution:

Open blog/user.js and paste following codes or make changes near hw3.3

/* The PostsDAO must be constructed with a connected database object */
function PostsDAO(db) {
    "use strict";

    /* If this constructor is called without the "new" operator, "this" points
     * to the global object. Log a warning and call it correctly. */
    if (false === (this instanceof PostsDAO)) {
        console.log('Warning: PostsDAO constructor called without "new" operator');
        return new PostsDAO(db);
    }

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

    this.insertEntry = function (title, body, tags, author, callback) {
        "use strict";
        console.log("inserting blog entry" + title + body);

        // fix up the permalink to not include whitespace
        var permalink = title.replace( /\s/g, '_' );
        permalink = permalink.replace( /\W/g, '' );

        // Build a new post
        var post = {"title": title,
                "author": author,
                "body": body,
                "permalink":permalink,
                "tags": tags,
                "comments": [],
                "date": new Date()}

        // now insert the post
        // hw3.2 TODO

        //Solution:
        //callback(Error("insertEntry NYI"), null);
        posts.insert(post,function(err,result){
            if(!err){
                console.log("Post inserted " + result[0].permalink);
                return callback(null, result[0].permalink);
            }
            return callback(err, null);
        });
    }

    this.getPosts = function(num, callback) {
        "use strict";

        posts.find().sort('date', -1).limit(num).toArray(function(err, items) {
            "use strict";
            if (err) return callback(err, null);
            console.log("Found " + items.length + " posts");
            callback(err, items);
        });
    }

    this.getPostsByTag = function(tag, num, callback) {
        "use strict";

        posts.find({ tags : tag }).sort('date', -1).limit(num).toArray(function(err, items) {
            "use strict";

            if (err) return callback(err, null);

            console.log("Found " + items.length + " posts");

            callback(err, items);
        });
    }

    this.getPostByPermalink = function(permalink, callback) {
        "use strict";
        posts.findOne({'permalink': permalink}, function(err, post) {
            "use strict";

            if (err) return callback(err, null);

            callback(err, post);
        });
    }

    this.addComment = function(permalink, name, email, body, callback) {
        "use strict";

        var comment = {'author': name, 'body': body}

        if (email != "") {
            comment['email'] = email
        }

        // hw3.3 TODO
        //callback(Error("addComment NYI"), null);
        var query = { "permalink" : permalink };
        var operator = { '$push' : { 'comments' : comment } };
        posts.update(query, operator, function(err, updated){
            "use strict"
            if(err)
                return callback(err, null);
            //console.log("Comment: " + comment.body + " inserted in post: " + permalink );
            console.log("Comment: " + updated);
            return callback(null, updated);
        });
    }
}

module.exports.PostsDAO = PostsDAO;

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exit mobile version