gpt4 book ai didi

node.js - 在 expressjs 中构建管理面板,无需大量查询即可计算用户数量的最佳方式?

转载 作者:可可西里 更新时间:2023-11-01 10:44:02 25 4
gpt4 key购买 nike

所以我正在为我的应用构建一个管理面板。在 admin 的主页上,我想显示一些有关使用情况的统计信息。

示例:24 小时、7 天、30 天、所有时间的注册注册方式:user/pass、facebook、twitter等

现在在我的 admin.index 路由器中,我正在异步调用我的数据库(使用 mongoose 的 mongodb)以获取所有计数,并在最终回调函数中渲染页面。

exports.index = function(req, res){
async.parallel({
// https://github.com/caolan/async#parallel
// counts number of users in date ranges
all_time: function(next) {
console.log('querying');
User.count({}, function (err, count) {
if (err) return next(err);
next(null, count);
});
},
past_day: function(next) {
console.log('querying');
User.count({'created_at': {$gte: yesterday}}, function(err, count) {
if (err) return next(err);
next(null, count);
});
},
week: function(next) {
console.log('querying');
User.count({'created_at': {$gte: week}}, function(err, count) {
if (err) return next(err);
next(null, count);
});
},
month: function(next) {
console.log('querying');
User.count({'created_at': {$gte: month}}, function(err, count) {
if (err) return next(err);
next(null, count);
});
},
// Counts number of user signups for each strategy
local: function(next) {
console.log('querying');
User.count({'strategy': 'local'}, function(err, count) {
if (err) return next(err);
next(null, count);
});
},
google: function(next) {
console.log('querying');
User.count({'strategy': 'google'}, function(err, count) {
if (err) return next(err);
next(null, count);
});
},
facebook: function(next) {
console.log('querying');
User.count({'strategy': 'facebook'}, function(err, count) {
if (err) return next(err);
next(null, count);
});
},
twitter: function(next) {
console.log('querying');
User.count({'strategy': 'twitter'}, function(err, count) {
if (err) return next(err);
next(null, count);
});
}
},
function(err, r) {
if (err) throw err;
res.render('admin/index', {
appName: Constants.APP_NAME,
title: 'Admin',
total_users: r.all_time,
yesterday: r.past_day,
week: r.week,
month: r.month,
local: r.local,
google: r.google,
facebook: r.facebook,
twitter: r.twitter
})
}
);
}

但就像现在一样,我在每次加载页面时都进行计算(8 个查询)。什么是更好的方法?我从未构建过 CRUD 应用程序,所以了解不多。我也没有使用 express 和 node 的经验,所以不知道它在这里是如何工作的。

我应该使用 memcached,还是矫枉过正?这将如何与异步一起工作?

最佳答案

首先,尽可能优化是好的,看看 $or operator .也许您只能使用一个请求,具体取决于您的数据结构。如果你不能,你可以制作一个只有计数的文档,查询这个文档,你可以在一个小请求中获得所有计数。

但我认为这里的这种优化是没有必要的。这些查询是针对管理员的。假设您有 1 位管理员和 10,000 位用户连接到您的网站,这些查询不是针对用户,而是针对您,有时您会使用;影响微不足道。

此外,您的查询受益于异步这一事实,因此您的应用可以同时响应其他用户。

关于node.js - 在 expressjs 中构建管理面板,无需大量查询即可计算用户数量的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com