简体   繁体   中英

Mongoose only sorting dates by time

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!

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM