Sotaro KARASAWA 10 лет назад
Родитель
Сommit
62b56e112b
2 измененных файлов с 48 добавлено и 0 удалено
  1. 31 0
      lib/models/comment.js
  2. 17 0
      lib/models/page.js

+ 31 - 0
lib/models/comment.js

@@ -86,5 +86,36 @@ module.exports = function(crowi) {
     });
     });
   };
   };
 
 
+  commentSchema.statics.countCommentByPageId = function(page) {
+    var self = this;
+
+    return new Promise(function(resolve, reject) {
+      self.count({page: page}, function(err, data) {
+        if (err) {
+          return reject(err);
+        }
+
+        return resolve(data);
+      });
+    });
+  };
+
+  /**
+   * post save hook
+   */
+  commentSchema.post('save', function(savedComment) {
+    var Page = crowi.model('Page')
+      , Comment = crowi.model('Comment')
+    ;
+
+    Comment.countCommentByPageId(savedComment.page)
+    .then(function(count) {
+      return Page.updateCommentCount(savedComment.page, count);
+    }).then(function(page) {
+      debug('CommentCount Updated', page);
+    }).catch(function() {
+    });
+  });
+
   return mongoose.model('Comment', commentSchema);
   return mongoose.model('Comment', commentSchema);
 };
 };

+ 17 - 0
lib/models/page.js

@@ -39,6 +39,7 @@ module.exports = function(crowi) {
     creator: { type: ObjectId, ref: 'User', index: true },
     creator: { type: ObjectId, ref: 'User', index: true },
     liker: [{ type: ObjectId, ref: 'User', index: true }],
     liker: [{ type: ObjectId, ref: 'User', index: true }],
     seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
     seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
+    commentCount: { type: Number, default: 0 },
     createdAt: { type: Date, default: Date.now },
     createdAt: { type: Date, default: Date.now },
     updatedAt: Date
     updatedAt: Date
   });
   });
@@ -164,6 +165,22 @@ module.exports = function(crowi) {
     });
     });
   };
   };
 
 
+  pageSchema.statics.updateCommentCount = function (page, num)
+  {
+    var self = this;
+
+    return new Promise(function(resolve, reject) {
+      self.update({_id: page}, {commentCount: num}, {}, function(err, data) {
+        if (err) {
+          debug('Update commentCount Error', err);
+          return reject(err);
+        }
+
+        return resolve(data);
+      });
+    });
+  };
+
   pageSchema.statics.getGrantLabels = function() {
   pageSchema.statics.getGrantLabels = function() {
     var grantLabels = {};
     var grantLabels = {};
     grantLabels[GRANT_PUBLIC]     = '公開';
     grantLabels[GRANT_PUBLIC]     = '公開';