Meteor - publish a collection's documents based on another collection's data

时间:2018-04-20 00:39:37

标签: mongodb meteor

I'm building an app (using Meteor) in which users can receive tasks and get points. The app has a leaderboard showing the points & ranks of the current user and 2 more users below and above him in the leaderboard. Here's an example:

LEADERBOARD
rank....user...................points
3.........user A...............100
4.........user B...............80
5.........user C...............60 (current user)
6.........user D...............40
7.........user E...............15

Let's say I want to retrieve the leaderboard of this month, here are the steps:
- Fetch user C document in Meteor.users collection
- Fetch the done tasks of user C in this month
- Sum the points of user C's tasks to get his points
- Base on user C's points, fetch two users below him (has less points) and above him (has more points) => HOW TO DO THIS ?
- Return 5 users to the client

I'm stuck at step 4 and looking forward to your suggestions. Thanks !

1 个答案:

答案 0 :(得分:0)

  • 在Meteor.users集合中获取用户C文档:

    let userC = Meteor.users.findOne(username : 'userC');
    
  • 在本月获取用户C的完成任务:

     let tasksUserC = Tasks.find({userId : userC._id}).fetch()
    

(假设您的任务有一个userId字段 - 如果是uniques用户名,则可以与用户名相同)

  • 总结用户C获得积分的任务要点

     let userCPoints = 0;
        for (let i = 0; i < tasksUserC.length; i++) {
            userCPoints += tasksUserC[i].point;
         }
    
  • 根据用户C点,获取他下面的两个用户(分数较少)和他上方(有更多分数)=&gt;怎么做?

    let allUsers = Meteor.users.find({}).fetch();
    allUsers.sort((a,b) => { return a.points - b.points });
    let indexOfUserC = allUsers.indexOf(userC);
    let fiveNeededUsers = allUsers[indexOfUserC - 2; indexOfUserC + 2];
    
  • 将5位用户返回客户端:

    return fiveNeededUsers;
    

没有尝试过,但如果你适应数据库中的字段,就应该这样做。