AndrewLeonardi
AndrewLeonardi

Reputation: 3512

Sorting with Mongo

I am trying to sort my MongoDB data. I have a rentals Schema shown below which includes a "featured" item. IF the featured item is set to true (users can do this on their end) I want the featured item to be shown above the rest of the Rentals. In other words I need to sort the mongo data that has featured = true to the top.

How would I change my code below to do this?

Here is my rental Schema:

var rentalsSchema = new mongoose.Schema({
    featured: {
        type: Boolean,
        default: false
    },
    Title: String,
});

Here is what I've tried so far (and is not working.)

router.get('/rentals', function(req, res) {
    db.collection('rentals').find().sort({
        featured: 1
    }).toArray(function(err, items) {

    });
});

Upvotes: 2

Views: 1489

Answers (1)

Pat Needham
Pat Needham

Reputation: 5918

Change .sort({ featured: 1 }) to .sort({ featured: -1 }). You want those with featured value of true to come before those with false false.

It looks like default sorting by boolean fields goes from false to true (maybe because of 0 and 1 numerical values, and default ascending order). To demonstrate this, open the Chrome Dev Tools console, enter [true, false, false, true].sort(), and the result is [false, false, true, true].

Upvotes: 5

Related Questions