MongoDB排序返回未定义

没有排序的leaderList返回未排序的数据。我尝试使用排序,但返回未定义。我想返回排序后的数据。

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});
    }
})

这是未排序的数据

[
    {
        "_id": "5eb8922d17d98c2bb6f98a5a",
        "username": "kk",
        "score": 20
    },
    {
        "_id": "5eb8922d17d98c2bb6f98a5b",
        "username": "mj",
        "score": 18
    },
    {
        "_id": "5eb8922d17d98c2bb6f98a5c",
        "username": "vr",
        "score": 15
    },
    {
        "_id": "5eb8922d17d98c2bb6f98a5d",
        "username": "mdb",
        "score": "25"
    }
]
评论
  • 有你的幸福
    有你的幸福 回复

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

    更改

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

    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);
      });