From a578d4f9100f0973568c8a3a18896776195aae1d Mon Sep 17 00:00:00 2001 From: "Chen, Tai-Lin" Date: Mon, 11 Dec 2023 01:09:06 +0800 Subject: [PATCH] fix: analytics completed rate --- packages/analytics/src/models/profiles.js | 58 +++++++++++++++++++---- 1 file changed, 48 insertions(+), 10 deletions(-) diff --git a/packages/analytics/src/models/profiles.js b/packages/analytics/src/models/profiles.js index 31cbb67..cb95ff1 100644 --- a/packages/analytics/src/models/profiles.js +++ b/packages/analytics/src/models/profiles.js @@ -3,20 +3,58 @@ import { UserProfile } from '@linux-odyssey/models' export function totalQuests() { - return UserProfile.find().count() + return UserProfile.aggregate([ + { + $project: { + _id: 0, + progress: { $objectToArray: '$progress' }, + }, + }, + { + $unwind: '$progress', + }, + { + $group: { + _id: null, + totalCount: { $sum: 1 }, + }, + }, + ]).then((results) => { + if (results.length === 0) { + throw new Error('No documents found') + } + return results[0].totalCount + }) } export function totalCompleted() { - return UserProfile.find({ - $where: function () { - for (const key in this.progress) { - if (this.progress[key].completed === true) { - return true - } - } - return false + return UserProfile.aggregate([ + { + $project: { + _id: 0, + progress: { $objectToArray: '$progress' }, + }, }, - }).count() + { + $unwind: '$progress', + }, + { + $match: { + 'progress.v.completed': true, + }, + }, + { + $group: { + _id: null, + totalCount: { $sum: 1 }, + }, + }, + ]).then((results) => { + if (results.length === 0) { + throw new Error('No documents found') + } + return results[0].totalCount + }) } export function userProfileList() {