0

I'm trying to make a query to my teams app that do this:

  1. Create a function that repeats in a certain time - DONE
    var now = new Date()
    var timeToEndOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999) - now;
    if (timeToEndOfDay < 0) {
         timeToEndOfDay += 86400000; 
    }
    setTimeout(async function(){
        // the mongo query will be here
    }, timeToEndOfDay);
  1. Get the user with the most votes for each team (the team is the value of the user_team_nickname_at field) - Half Done

  2. Assign points to each of those users - NOT DONE

Note 1: if the user wins 2 times (the user can do a post with a team and then change a team and post, the points will be assigned to the post that had the most votes, therefore the next user in votes will win

Note 2 the user_team_nickname_at right now has 100 'teams' but this count is dynamic, eventually will have more 'teams'

Mongodb query

    const posts = await Posts.find()
    .select('user_team_nickname_at vote_up userid')
    .sort({vote_up:-1})
    .where({'user_team_nickname_at':'team One'})
    .limit(1)
    res.json({serverResponse:posts})

I need to find a way to iterate between where({'user_team_nickname_at':'dynamicVariable'}) to obtain the first winners of every user_team_nickname_at with the condition specified in Note 1

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Alex Hunter
  • 212
  • 9
  • 30
  • You want `aggregate()` here, and "group by" the "nickname". i.e `Posts.aggregate([{ "$sort": { "user_team_nickname": 1, "vote_up": -1 } }, { "$group": { "_id": "$user_team_nickname", "vote_up": { "$first": "$vote_up" }, "userid": { "$first": "$userid } }}])`. That returns the **top 1** for each score by the "nickname". For the **top N** results ( more than one per group ), see [mongodb group values by multiple fields](https://stackoverflow.com/a/22935461/2313887) – Neil Lunn Nov 02 '19 at 00:32
  • hey, excuse me, can you please check your query? im getting an error @NeilLunn – Alex Hunter Nov 02 '19 at 00:57
  • It is missing a quote after `"$userid`, which should be `"$userid"`. But that's just base syntax, and I do type things in comments without running through an editor. You really should be looking at referenced answers and the documentation links within them rather than expecting to directly copy and paste code. Reading the content will help you understand why the statement works. – Neil Lunn Nov 02 '19 at 01:05

0 Answers0