javascriptmongodbmongooseleaderboard

Leaderboard from database using MongoDB/Mongoose


In each document there is a level field with a Number value and a twitch_username with a String value. I want to return these values like so:

1. Twitch: <twitch_username> Level: <level>
2. Twitch: <twitch_username> Level: <level>
3. Twitch: <twitch_username> Level: <level>
//...

I tried mapping through the data, running a for loop, pushing the data into a new array, etc. but can't seem to wrap my head around it.

Currently running this query which returns the specific data I need in descending order:

  User.find({}).select('twitch_username level -_id').sort({level: 'desc'}).exec((err,docs) => { 
      // console.log(docs);
  });

The query above returns:

[
  { twitch_username: 'user1', level: 67 },
  { twitch_username: 'user2', level: 14 }
]

Which is sort of what I want but I can't individually label each value, the data is returned but I can't do anything with it.


Solution

  • You can use array reduce to reduce it to a string

    const output = [
      { twitch_username: 'user1', level: 67 },
      { twitch_username: 'user2', level: 14 }
    ];
    

    Then use reduce function

    output.reduce((final, current, id) => {
        return (final + (id+1) + '. Twitch: ' + current.twitch_username + ' Level: ' + current.level + '\n');
    }, '')