I was looking for a way to sort array of object by an arbitrary list. Lets assume I have this array of objects.
[
{
"_id": "4JEEuhNIae",
"category": "grocery"
},
{
"_id": "4JW7miNITl",
"category": "food"
},
{
"_id": "4Je4kmrrbZ",
"category": "coffee"
},
{
"_id": "4JgAh3N86x",
"category": "coffee"
}
]
This is the array that I would like to use as sorting criteria. Records with foodshould come first, then coffeeand grocery.
['food','coffee','grocery']
Result should be:
[
{
"_id": "4JW7miNITl",
"category": "food"
},
{
"_id": "4Je4kmrrbZ",
"category": "coffee"
},
{
"_id": "4JgAh3N86x",
"category": "coffee"
},
{
"_id": "4JEEuhNIae",
"category": "grocery"
},
]
How can I do this type of sorting on mongodb by using mongoose? I really don't want to make any operations on the code after fetching data.