How to sort two fields with mongoose?
<p>I'm trying to allow users to see trending posts. The general idea is to sort by the most recent posts (_id: -1) and then sort those by most upvotes (upvotes_count: -1) and then limiting the results (.limit(3)). This is a bit simplified, so please ignore this implementation of "trending posts".</p>

<p>Unfortunately, I'm not able to return two sorts in the way that I want. So with a collection of six posts, it returns the most recent three, but it doesn't then sort them by most upvotes. For instance:</p>

<p>Post 6 (upvotes: 1)
Post 5 (upvotes: 2)
Post 4 (upvotes: 1)</p>

<p>I want them to be sorted like so:</p>

<p>Post 5 (upvotes: 2)
Post 6 (upvotes: 1)
Post 4 (upvotes: 1)</p>

<p>I'm not so interested in what happens with ties, but at a minimum, I want the posts that have more upvotes to be listed higher than those with less upvotes. </p>

<p>Of course, I could write a method to sort these, but surely there is a way to do this with MongoDB.</p>

<p>Below are some of the ways I've tried to implement this sort. </p>

<pre><code>// Use sort for date and then use it again for upvotes_count
Post.find()
    .sort({_id: -1})
    .sort({upvotes_count: -1})
    .limit(3)
    .exec( function(err, posts) {
        if (err) res.send(err);
        console.log(posts);
        res.json(posts);
     });

// Use sort for date, limit the results to three, and then
// use it again for upvotes_count
Post.find()
    .sort({_id: -1})
    .limit(3)
    .sort({upvotes_count: -1})
    .exec( function(err, posts) {
        if (err) res.send(err)
        console.log(posts);
        res.json(posts);
    });

// Use sort for date and upvotes_count in one step.
Post.find()
    .sort({_id: -1, upvotes_count: -1})
    .limit(3)
    .exec( function(err, posts) {
        if (err) res.send(err);
        console.log(posts);
        res.json(posts);
     });
</code></pre>

<p>None have worked.</p>