在NodeJS中,有没有更好/更优的方法从Mongo中获取多个查询?我为每个用户循环运行这段代码,所以当我的用户群增长时,我担心这段代码的性能和可靠性。
const cron = require('node-cron');
cron.schedule(process.env.SCHEDULE_TIME, async () => calculateUserHonors(), {
scheduled: true,
timezone: 'Europe/Prague',
});
const calculateUserHonors = async () => {
// for loop for every user in database
let pollVotesCount, commentVotesCount, sharesCount, commentsCount, blogCount;
const pollVotesPromise = getPollVoteCount(dbClient, userId);
const commentVotesPromise = getCommentVotesCount(dbClient, userId);
const sharesPromise = getShareLinkCount(dbClient, userId);
const commentsPromise = getCommentedCount(dbClient, userId);
const blogPromise = getBlogCount(dbClient, userId);
Promise.all([pollVotesPromise, commentVotesPromise, sharesPromise, commentsPromise, blogPromise]).then((values) => {
pollVotesCount = values[0];
commentVotesCount = values[1];
sharesCount = values[2];
commentsCount = values[3];
blogCount = values[4];
});
const getPollVoteCount = async (dbClient, userId) => dbClient.db().collection('poll_votes').find({ user: userId }).count();
const getCommentVotesCount = async (dbClient, userId) => dbClient.db().collection('comment_votes').find({ 'user.id': userId }).count();
const getShareLinkCount = async (dbClient, userId) => dbClient.db().collection('link_shares').find({ user: userId }).count();
const getCommentedCount = async (dbClient, userId) => dbClient.db().collection('comments').find({ 'user.id': userId }).count();
const getBlogCount = async (dbClient, userId) => dbClient.db().collection('items').find({ 'info.author.id': userId }).count();发布于 2020-08-26 02:46:43
您应该查看聚合管道:https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/
例如,要获取poll_votes
dbClient.db().collection('poll_votes').aggregate([
{ $group: { _id: '$user', count: { $sum: 1 } } },
{ $addFields: { user: '$_id', pollVotes: '$count' } }
]);您将获得一个包含每个用户的投票结果的数组。
https://stackoverflow.com/questions/63584970
复制相似问题