فهرست منبع

use aggregation of PageTagRelation

yusuketk 7 سال پیش
والد
کامیت
07a2424cfc
3فایلهای تغییر یافته به همراه14 افزوده شده و 16 حذف شده
  1. 9 0
      src/server/models/page-tag-relation.js
  2. 3 15
      src/server/models/tag.js
  3. 2 1
      src/server/routes/tag.js

+ 9 - 0
src/server/models/page-tag-relation.js

@@ -37,6 +37,15 @@ class PageTagRelation {
     }
     }
   }
   }
 
 
+  static async createTagListWithCount(opt) {
+    const count = await this.aggregate()
+      .group({ _id: '$relatedTag', count: { $sum: 1 } })
+      .sort(opt.sortOpt)
+      .skip(opt.offset)
+      .limit(opt.limit);
+    return count;
+  }
+
 }
 }
 
 
 module.exports = function() {
 module.exports = function() {

+ 3 - 15
src/server/models/tag.js

@@ -30,22 +30,10 @@ class Tag {
     return tag;
     return tag;
   }
   }
 
 
-  static async findList(option) {
+  static async findList(opt) {
     const PageTagRelation = Tag.crowi.model('PageTagRelation');
     const PageTagRelation = Tag.crowi.model('PageTagRelation');
-    const result = {};
-    result.tags = await this.aggregate([
-      {
-        $addFields: {
-          pageCount: await PageTagRelation.find({
-            _id: '$_id',
-          }),
-        },
-      },
-    ])
-      .sort({ pageCount: 1 }).skip(option.offset).limit(option.limit);
-
-    result.totalCount = await this.count();
-    return result;
+    const list = await PageTagRelation.createTagListWithCount(opt);
+    return list;
   }
   }
 
 
 }
 }

+ 2 - 1
src/server/routes/tag.js

@@ -35,7 +35,8 @@ module.exports = function(crowi, app) {
   api.list = async function(req, res) {
   api.list = async function(req, res) {
     const limit = +req.query.limit || 50;
     const limit = +req.query.limit || 50;
     const offset = +req.query.offset || 0;
     const offset = +req.query.offset || 0;
-    const queryOptions = { offset, limit };
+    const sortOpt = { count: -1 };
+    const queryOptions = { offset, limit, sortOpt };
 
 
     try {
     try {
       const result = await Tag.findList(queryOptions);
       const result = await Tag.findList(queryOptions);