ServerSideSkittles
ServerSideSkittles

Reputation: 2973

MongoDB - Fetch top 5 fields of a leaderboard

I have a very simple table which outputs the data as

{
_id: 55dbdffeaba8ee274d3b9f89,
    firstname: 'Jim',
    lastname: 'Kirk',
    email: '[email protected]',
    points: 3333,
}

I have about 10 records in my database so far. I use the following var to create user model.

var User = mongoose.model('User', userSchema);

I want to sort the points by the most and display the top 5 at any given time..store as a variable and pass through to express/ejs as an array.

So far I have this query but when I console.log I get undefined.

var leaderboard = User.find( {points: {$exists: true}} ).sort({points : -1}).limit(5);

Update: Upon running this query in Robomongo I get 5 records with all data, but a console.log returns the data 'undefined'. How can I output data as array to put into a table and also filter out the _id and email?

Upvotes: 1

Views: 2402

Answers (2)

AaronLight
AaronLight

Reputation: 423

The issue is after

var leaderboard = User.find( {points: {$exists: true}} ).sort({points : -1}).limit(5);

get's executed leaderboard contains a cursor. Append .toArray() to the end of the command and you should be good to go. Your final command should look like this:

var leaderboard = User.find( {points: {$exists: true}} ).sort({points : -1}).limit(5).toArray();

Check out the documentation for more information.

Upvotes: 4

dimzon
dimzon

Reputation: 424

Seems like you mess "points" and "score" document fields.

Upvotes: 0

Related Questions