Mongodb sort returning undefined

Viewed 195

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"
    }
]
2 Answers

chain the .sort() before .find({})

change

const leadersList = await db.collection('leaders').sort(sort).find({}).toArray();

to

const leadersList = await db.collection('leaders').find({}).sort(sort).toArray();

also you can try this without chain .sort():

  var collection = db.collection('leaders');

  var options = {
    "sort": { "score": -1 },
  };
  collection.find({},options).toArray(function(err, data) {
    if (err) {
      console.log(err);
    }
    console.log(data);
  });

If you use sort() directly on a collection then you may get the below error: "...sort is not a function" because it has to be applied on a result set not on a collection directly. Hence, it should be used after find(). Sample query to sort books based on price:

db.books.find().sort({"price":-1}).toArray()

Hence, in this case, you should query like below:

db.collection('leaders').find({}).sort({"score": -1}).toArray();
Related