Search code examples
javascriptmongodbexpressmongooseexpress-router

How to implement a MongoDB sort when using express router


I am trying to use one of MongoDB's default sorting algorithms within a Model.find(), however I cannot figure out how to implement the sorting feature in this way. I know how it works and how to use it in the mongo command line but cannot figure out how to implement it in this manor.

This is the code I have so far, it works perfectly and returns the values that I want, however I now want to implement the sort that I have stored in mySort to sort the data returned.

const express = require('express'),
    router = express.Router(),
    House = require('../models/house'),
    Event = require('../models/event');

router.get('/', function(req, res){

    var mySort = {totalPoints: -1};

    House.find({}, function(err, houses){
        if(err){
            console.log(err);
            res.redirect('/error');
        } else {
            res.render('houses/index', {pageTitle: 'Houses', houses: houses});
        }
    });
});

module.exports = router;

I would expect that the houses would be returned in a manor with descending values for totalPoints.


Solution

  • Try this syntax :

    House
       .find()
       .sort("-totalPoints") // or { "totalPoints" : -1 }
       .exec( houses => ... )
    

    or with async/await :

    const houses = await House.find().sort("-totalPoints")