-1

I have created a GET api for results, with filters, pagination and sorting. But though the data is correct, the sorting is not happening correctly.

let skip = 0, limit = 10, findCond = {centerId: self.centersModel.getObjectId(userData.id)};
if(queryParams.result) findCond['result'] = {"$regex": queryParams.result, "$options": 'i'};

if(queryParams.fromDate) findCond['created_at'] = {$gte: moment(queryParams.fromDate + ' 00:00:00', 'DD-MM-YYYY HH:mm:ss').toDate()};
if(queryParams.toDate) {
    if(findCond.hasOwnProperty('created_at')) findCond['created_at']['$lte'] = moment(queryParams.toDate + ' 23:59:59', 'DD-MM-YYYY HH:mm:ss').toDate();
    else findCond['created_at'] = {$lte: moment(queryParams.toDate + ' 23:59:59', 'DD-MM-YYYY HH:mm:ss').toDate()};
}

if(queryParams.perPage) limit = parseInt(queryParams.perPage);
if(queryParams.page) skip = (parseInt(queryParams.page) - 1) * limit;

let aggregate = [
    { "$match": findCond },
    { "$sort": {"created_at": 1} },
    { "$skip": skip },
    { "$limit": limit }
];
console.log(aggregate)
self.resultsModel.aggregate(aggregate, function(err, results) {
    console.log(err, results);
});

Result:

{
    "status": "ok",
    "results": [
        {
            "id": "5db83e69fcee977a20b24260",
            "result": "Pass",
            "examDate": "29/10/2019 06:58 PM"
        },
        {
            "id": "5db6b4d33ffd7d3ccde175d1",
            "result": "Pass",
            "examDate": "28/10/2019 08:38 PM"
        },
        {
            "id": "5db83e9bfcee977a20b24262",
            "result": "Pass",
            "examDate": "29/10/2019 06:58 PM"
        },
        {
            "id": "5db83ecafcee977a20b24264",
            "result": "Pass",
            "examDate": "29/10/2019 06:59 PM"
        },
        {
            "id": "5db83f40fcee977a20b24266",
            "result": "Fail",
            "examDate": "29/10/2019 07:01 PM"
        },
        {
            "id": "5db84395bb402b0f3de43ff7",
            "result": "Pass",
            "examDate": "29/10/2019 07:20 PM"
        },
        {
            "id": "5db843c0bb402b0f3de43ff9",
            "result": "Pass",
            "examDate": "29/10/2019 07:20 PM"
        }
    ]
}

One of the date is 28/10/2019 in between 29/10. Please tell me a reason or a solution to this.

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92

1 Answers1

0

I think, to reduce confusion, you should share the value of aggregate variable that you have logged, rather than the response you create after applying a transformation to it.