leadersList without the sort returns the data unsorted. I tried using sort but it returns undefined. I would like to get the sorted data returned.
app.get('/api/leaders/', async (req, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true, useUnifiedTopology: true});
const db = client.db('leaders');
var sort = {score: -1};
const leadersList = await db.collection('leaders').sort(sort).find({}).toArray();
res.status(200).json(leadersList);
client.close();
} catch (error) {
res.status(500).json({message: 'Error connecting to db', error});
}
})
Here is the unsorted data
[
{
"_id": "5eb8922d17d98c2bb6f98a5a",
"username": "kk",
"score": 20
},
{
"_id": "5eb8922d17d98c2bb6f98a5b",
"username": "mj",
"score": 18
},
{
"_id": "5eb8922d17d98c2bb6f98a5c",
"username": "vr",
"score": 15
},
{
"_id": "5eb8922d17d98c2bb6f98a5d",
"username": "mdb",
"score": "25"
}
]