I have a Meteor Publication which returns a set of products from a collection. Each document contains a field called 'grade' for which we have assigned a string value of 'S', 'A', 'B', 'C', or 'D'. Each Grade tier represents a more broad condition of an item where 'S' is the best possible condition, 'A' is the next best, then 'B', and so on...
When I return the collection, I want to sort by the grade. Obviously it would not make any sense for MongoDB to have S-Grade products appear first on the list by default, because A, B, C, and D all come before S in standard alphabetical sorting.
Is there a way to set up custom sorting so that I can allow Grade-S items to appear at the top of the list of results during a sort, but also allowing A, B, C, and D to appear following in their proper order?
I don't think that mongodb offers a custom comparator for sorting, and I expect the performance of such operation would be poor anyway.
The best option is to use a numeric field for sorting purposes and, if needed, add the string for display purposes (and keep them in sync during document updates etc.).
You can avoid storing the string if you don't strictly need it in the database, and map the numeric value to the string whenever it needs to be displayed. Meteor lets you specify a transform in a query to a collection, and the platform will do the rest for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With