'Sequelize sort query by number
Hey stack overflow I have a query that I am making to my mysql database. I would like to order it by number. Here is what I currently have
const frequencies = await DeliveryFrequency.findAndCountAll({
offset,
limit,
order: [['code', 'ASC']],
where: {
tenantId: filters.tenantId,
...(filters.frequencyCodes?.length > 0 ? { code: { [Op.in]: filters.frequencyCodes } } : {}),
},
});
My data set looks like
{
"data": [
{
"id": "d8fb16b5-3b49-415b-8036-43d15a2505d3",
"code": "1",
"translations": {
"en": {
"displayText": "1 month"
}
},
"displayText": "1 month",
"language": "en"
},
{
"id": "bfac3cd9-95dd-4919-98ac-c9f3d6e0874d",
"code": "10",
"translations": {
"en": {
"displayText": "10 days"
}
},
"displayText": "10 days",
"language": "en"
},
{
"id": "2548e225-53bf-417c-8f0e-9fc7df21061b",
"code": "45",
"translations": {
"en": {
"displayText": "45 days"
}
},
"displayText": "45 days",
"language": "en"
},
{
"id": "89a49423-779c-4a56-9b7e-28fafce0202a",
"code": "5",
"translations": {
"en": {
"displayText": "5 days"
}
},
"displayText": "5 days",
"language": "en"
}
],
"offset": 0,
"limit": 20,
"totalCount": 4
}
I want to numerically sort the 'code' property as 1, 5, 10, 45. However when I do order: [['code', 'ASC']] it doesnt order them properly. Its ordered in my code example shown above. Any ideas or approach on how I can sort numerically?
Solution 1:[1]
If you are sure that code always stores integer numbers as strings you can use Sequelize.cast like this:
order: [[Sequelize.cast('code', 'integer'), 'ASC']]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anatoly |
