1

I am running a Node.JS server which uses Mongoose to query a MongoDB table that contains a date field. However, when I sort the results by date, they are actually only sorted by the time, disregarding the actual date. For example when I run the query

    Competition.find({})
        .sort('date')
        .exec()
        .then(data => {
            res.json(data);
        })
        .catch(console.log);

It returns:

{"_id":"5c6c99e6e7179a27eb63a9a0","date":"2019-02-24T01:00:00.000Z","game_name":"UFO","status":"WAITING","comp_id":7}, 

{"_id":"5c6b95c8e7179a27eb62e7cf","date":"2019-02-19T06:41:47.185Z","game_name":"UFO","status":"COMPLETED","comp_id":6}, 

{"_id":"5c6b95b4e7179a27eb62e7cb","date":"2019-02-19T06:41:57.174Z","game_name":"UFO","status":"COMPLETED","comp_id":5}, 

{"_id":"5c6b95a4e7179a27eb62e7be","date":"2019-02-19T06:42:02.170Z","game_name":"UFO","status":"COMPLETED","comp_id":4}, 

{"_id":"5c6b9533e7179a27eb62e7a9","date":"2019-02-19T06:42:07.176Z","game_name":"UFO","status":"COMPLETED","comp_id":1}, 

{"_id":"5c6b958de7179a27eb62e7b8","date":"2019-02-21T18:48:50.497Z","game_name":"UFO_test","status":"COMPLETED","comp_id":3}

You can see here that the first entry has a date of 02-24 so it should show up last, but since the time is 1:00:00 it shows up before the other entries with the dates 02-19 and 02-21, since their times are later (06:41:47 for example).

The schema for the competition table is as follows:

    const schema = new mongoose.Schema({
      date: Date,
      game_name: String,
      status: String,
      comp_id: Number,
    });

I've tried to execute the date sort in a few different ways that Mongoose supports, but they all return the same results. If anyone could provide a fix or a workaround for this issue it would be greatly appreciated!

Sam Hollenbach
  • 652
  • 4
  • 19
  • 1
    Possible duplicate of [In Mongoose, how do I sort by date? (node.js)](https://stackoverflow.com/questions/5825520/in-mongoose-how-do-i-sort-by-date-node-js) – kRiZ Feb 22 '19 at 07:06
  • 1
    Try saving the date using moments or epoch to save the dates. The problem lies in how you save the date. – kRiZ Feb 22 '19 at 07:07

1 Answers1

1

I had a similar problem and in my case, the dates were not saved as date in mongo like so:

"createdAt": {
  "$date": "2018-04-25T22:48:06.863Z"
}

It could be related to the way you are creating your date object. Are you using moment or new Date() or anything else?

erwan
  • 311
  • 1
  • 3
  • 9
  • This was exactly the issue. The problematic date was being saved as milliseconds since epoch instead of date objects. Thanks! – Sam Hollenbach Feb 23 '19 at 21:32