2

We have a collection "packages" like the following:

|          package            | version | released |
| --------------------------- | ------- | -------- |
| 'https://example.com/a.pkg' | '1.0.0' |   true   |
| 'https://example.com/b.pkg' | '2.0.0' |   true   |
| 'https://example.com/c.pkg' | '3.0.0' |   true   |
| 'https://example.com/d.pkg' | '4.0.0' |   true   |

Now, we need to find the highest version. So we write down the code:

find({ released: true }).sort({ version: -1 }).limit(1)

But, quickly, we find it does not work. Since sort uses string comparison, it is not what we expect. What we expect is version comparison, which is a customized function (javascript).

Finally, the question is: how to write customized comparator function?

Jim Jin
  • 1,249
  • 1
  • 15
  • 28
  • I think duplicate with [mongoose/mongodb custom sort](https://stackoverflow.com/questions/14720484/mongoose-mongodb-custom-sort) – techstack May 25 '20 at 12:12
  • I tried the client-side way, but mongoose complains with an error message, "can't pass a function to sort()". – Jim Jin May 25 '20 at 15:44

0 Answers0