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

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

Making your blog accept posts

In this homework, you will be enhancing the blog project to insert entries into the posts collection. After this, the blog will have basic functionality. It will allow you to add blog posts with a title, body, and tags and have it be added to the posts collection properly.

We have provided the code that creates users and allows you to log in (the assignment from last week). Download and unpack the files for this homework from the Download Handout link.

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 hw3.2 with “hw3.2 TODO”.

In a terminal:

Linux/Mac:

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

Windows:

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

You should not need to touch any other code. The database call that you are going to add will insert a new post into the posts collection. Here is an example of a valid blog post:

> db.posts.find().pretty()
{
"_id" : ObjectId("513d396da0ee6e58987bae74"),
"title" : "Martians to use MongoDB",
"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.",
"permalink" : "martians_to_use_mongodb",
"tags" : [
"martians",
"seti",
"nosql",
"worlddomination"
],
"comments" : [ ],
"date" : ISODate("2013-03-11T01:54:53.692Z")
}

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

npm install
node app.js

To play with the blog you can navigate to the following URLs:

http://localhost:8082/
http://localhost:8082/signup
http://localhost:8082/login
http://localhost:8082/newpost

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/posts.js and paste following codes or make changes near hw3.2

/* 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