Eric
Eric

Reputation: 667

How do I sort 'auto-magically' using Mongoose?

Say I have a URL like this:

http://dev.myserver.com/systems?system_type.category=Penetration

which hits the following controller:

exports.findAll = function(req, res) { 
    System.find(req.query, function(err, systems) {
        res.send(systems);
    });
};

and then returns the set below 'auto-magically' using Node, Express, MongoDB and Mongoose:

[{
    "_id":            "529e5f29c128685d860b3bad",
    "system_number":  "123",
    "target_country": "USA",
    "system_type":     {
        "category":   "Penetration",
        "subcategory": ["Floor", "Wall"]
    }
},{
    "_id":            "999e5f29c128685d860b3bad",
    "system_number":  "456",
    "target_country": "Canada",
    "system_type":     {
        "category":   "Penetration",
        "subcategory": ["Floor", "Wall"]
    }
}]

Now, if I want the results sorted by 'target_country', what is the 'best practice' for 'auto-magically' doing that?

Are there certain parameters/syntax that Mongoose/Express are expecting to do it for me? Or, is this a case where I have to specifically code for it? (That would kill the 'auto-magical' functionality already there.)

Thanks!

UPDATE: Here is what worked for me.

exports.findAll = function(req, res) {

    // Sort Ascending: 
    http://dev.dom.com/systems?system_type.category=Penetration&sort=system_number

    // Sort Descending:
    http://dev.dom.com/systems?system_type.category=Penetration&sort=-system_number

    // Default sort ascending on system_number:
    http://dev.dom.com/systems?system_type.category=Penetration

    var sort_param = req.query.sort ? req.query.sort : 'system_number';

    System.find().sort(sort_param).find(function(err, menus) {        
        res.send(menus);
    });

};

I guess where I went wrong, was to think I should find with filters and then sort, instead of find all, sort and then find again with filters. Still getting my head wrapped around the whole 'callback philosophy' I guess.

Upvotes: 0

Views: 1499

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311905

You need to define separate URL parameters for the query and sort components of your System query. As in:

System.find(req.query.query).sort(req.query.sort).exec(function(err, systems) {
    res.send(systems);
});

Then you'd use request URL parameters that look like:

?sort=target_country
    &query[system_type.category]=Penetration
    &query[system_type.subcategory]=Floor

Docs on sort here.

Upvotes: 1

Related Questions