Maria Jane Maria Jane - 1 month ago 5
Node.js Question

mongoose sort doesn't work using find()

Sales.find({
"email":req.body.email,
"createAt": {
"$gte": firstDayOfMonth(month),
"$lte": lastDayOfMonth(month)
},
"sort":{
createAt: -1 //Sort by Date Added DESC
}
}, function(err,response){
callback(err,response);
});


Any clue why this mongoose query doesn't work? I'm sure it's sort problem coz when I remove the sort part I'm able to get some data.

Answer

Please try this code,

var queryOptions = {
    $and: [{
        'createAt': {
            "$gte": firstDayOfMonth(month),
            "$lte": lastDayOfMonth(month)

        }
    }, {
        'email': req.body.email
    }]
}
Sales
    .find(queryOptions)
    .sort('-createAt')
    .exec(function(err, response) {
        return res.status(200).json(response);

    }).catch(function(error) {
        return res.status(500).json(error);
    });