Node. js blog instance (10) pv statistics and message statistics
In post. js, modify var post = {...} To (after each change, clear e:/mongodb/blog ):
// Document var post = {name: this. name, time: time, title: this. title, post: this. post, tags: this. tags, comments: [], pv: 0 };
The pv key is added to the document to be stored and the initial value is 0.
Change post. getOne () in Post. js:
// Obtain an article Post. getOne = function (name, day, title, callback) {// open the database mongodb. open (function (err, db) {if (err) {return callback (err);} // read the posts set db. collection ('posts', function (err, collection) {if (err) {mongodb. close (); return callback (err);} // query collection by user name, posting date, and article name. findOne ({name: name, time. day: day, title: title}, function (err, doc) {if (err) {mongodb. close (); return callback (err);} // parse markdown to htmlif (doc) {collection. update ({name: name, time. day: day, title: title },{$ inc: {pv: 1 }}, function (err) {mongodb. close (); if (err) return callback (err) ;}); doc. post = markdown. toHTML (doc. post); doc. comments. forEach (function (comment) {comment. content = markdown. toHTML (comment. content) ;}) ;}callback (null, doc); // return a query Article });});});};
Note: collection. findOne ({
Name: name,
Time. day: day,
Title: title
}, Function (err, doc ){
If (err ){
Mongodb. close ();
Return callback (err );
}
Here, mongodb. close (); must be placed in if; otherwise, an error is returned:
Throw new Error ('can't set headers after they are sent .');
Error: Can't set headers after they are sent.
The reason is that NODEJS is asynchronous. Another mongodb. close () will be executed below, and errors will occur when two asynchronous statements are executed simultaneously ;.
Modify index. ejs, user. ejs, and article. ejs in:
<%-Post. post %>
Add a line of code in the next line:
Read: <% = post. pv %> | comment: <% = post. comments. length %>
At this point, the article displays the number of reads and comments: