The original tutorial Https://github.com/nswbmw/N-blog/wiki/_pages the tenth chapter, due to the version and other reasons, in the original tutorial based on a slight change can be achieved.
Post.js var post={...} Change to (empty the e:/mongodb/blog/after each change):
Document to be stored in the database var post = { name:this.name, time:time, title:this.title, post:this.post, Tags:this.tags, comments:[], pv:0 };
We add the PV key to the document to be stored and assign the initial value to 0 directly.
Continue to modify the Post.getone () in Post.js to:
Get an article Post.getone = function (name, day, title, callback) { //Open Database Mongodb.open (function (err, db) {if (err) {return Callback (err);} Read posts Collection db.collection (' posts ', function (err, collection) {if (err) {mongodb.close (); return callback (ERR);} Query based on user name, publication date and article name Collection.findone ({"Name": Name, "Time.day": Day, "title": Title}, function (Err, doc) {if (err) { Mongodb.close (); return callback (ERR);} Parse markdown for Htmlif (DOC) {collection.update ({"Name": Name, "Time.day":d ay, "title": title},{$inc: {"PV": 1}},function (ERR) {mongodb.close (); if (err) return callback (ERR);}); Doc.post=markdown.tohtml (doc.post);d Oc.comments.forEach (function (comment) {comment.content = markdown.tohtml ( comment.content);});} Callback (null, DOC);//return query for an article});});};
Note here: Collection.findone ({
"Name": Name,
"Time.day": Day,
"title": Title
}, function (Err, doc) {
if (err) {
Mongodb.close ();
Return callback (ERR);
}
Here Mongodb.close (); Be sure to put the if inside, otherwise you will get an error:
throw new Error (' can\ ' t set headers after they is sent. ');
Error:can ' t set headers after they is sent.
The reason is that nodejs asynchronous mechanism, there is another mongodb.close () will execute, two asynchronous simultaneous execution will be error;.
Modify Index.ejs, User.ejs, and Article.ejs by adding a line of code on the following line: <p><%-post.post%></p>:
<p class= "Info" > read: <%= post.pv%> | Comments: <%= post.comments.length%></p>
At this point, the article has a number of readings and comments on the display:
node. JS Blog Instance (10) PV statistics and message statistics