Home > other >  How do I sort by time(string) for Mongoose?
How do I sort by time(string) for Mongoose?

Time:09-17

I am trying to sort some documents depending on the field 'time'

This is the how I'm currently sorting the documents:

const users = await UserModel.find({}).sort('time');

So at the moment the data looks like this: (CSV format)

time,name
10:30 AM,John Smith
12:30 PM,Elsa Smith
2:30 PM,Jo Smith
8:30 AM,Gale Smith

However, it is being sorted based on the first number rather than the time. Unfortunately I don't have the luxury of changing the data type in the database to anything else other than string which it currently is.

It needs to be sorted correctly depending on the time like so:

time,name
8:30 AM,Gale Smith
10:30 AM,John Smith
12:30 PM,Elsa Smith
2:30 PM,Jo Smith

Any advice on how I can sort this?

CodePudding user response:

There is no in-built sort modifier in mongoose that I know of that can achieve your request.

A good workaround is to implement your own sorting function from the found results.

Here is a reference post: How to define a sort function in Mongoose

CodePudding user response:

const users = await UserModel.find({}).sort({'time': 'desc'}).exec();
 

From v3.8.1 :

const users = await UserModel.find({}).sort('time', -1).execFind();
  • Related