Browse Source

Commit 10-5: Denormalized the number of comments into the post.

- only handle comment insertions at this point
- fixtures need the commentsCount because they run server-side inserts.
Frederic G. MARAND 9 years ago
parent
commit
3161b98742

+ 0 - 4
client/templates/posts/post_item.js

@@ -17,9 +17,5 @@ Template.postItem.helpers({
     var a = document.createElement('a');
     a.href = this.url;
     return a.hostname;
-  },
-
-  commentsCount: function () {
-    return Comments.find({postId: this._id}).count();
   }
 });

+ 4 - 0
lib/collections/comments.js

@@ -26,6 +26,10 @@ Meteor.methods({
       author: user.username,
       submitted: new Date()
     });
+    Posts.update(comment.postId, {
+      $inc: { commentsCount: 1 }
+    });
+
     return Comments.insert(comment);
   }
 });

+ 2 - 1
lib/collections/posts.js

@@ -67,7 +67,8 @@ Meteor.methods({
     var post = _.extend(postAttributes, {
       userId: user._id,
       author: user.username,
-      submitted: new Date()
+      submitted: new Date(),
+      commentsCount: 0
     });
     var postId =  Posts.insert(post);
     return {

+ 6 - 3
server/fixtures.js

@@ -26,7 +26,8 @@ if (Posts.find().count() === 0) {
     userId: sacha._id,
     author: sacha.profile.name,
     url: "http://sachagreif.com/introducing-telescope",
-    submitted: new Date(now - 7 * 3600 * 1000)
+    submitted: new Date(now - 7 * 3600 * 1000),
+    commentsCount: 2
   });
 
   Comments.insert({
@@ -50,7 +51,8 @@ if (Posts.find().count() === 0) {
     userId: tom._id,
     author: tom.profile.name,
     url: "http://meteor.com",
-    submitted: new Date(now - 10 * 3600 * 1000)
+    submitted: new Date(now - 10 * 3600 * 1000),
+    commentsCount: 0
   });
 
   Posts.insert({
@@ -58,7 +60,8 @@ if (Posts.find().count() === 0) {
     userId: tom._id,
     author: tom.profile.name,
     url: "http://themeteorbook.com",
-    submitted: new Date(now - 12 * 3600 * 1000)
+    submitted: new Date(now - 12 * 3600 * 1000),
+    commentsCount: 0
   });
 }
 else {