I'm trying to output all object list from database with sequelize as follow and want to get data are sorted out as I added id in where clause.
exports.getStaticCompanies = function () { return Company.findAll({ where: { id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680] }, attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'] }); };
But the problem is after rendering, all data are sorted out as follow.
46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....
As I found, it's neither sorted by id nor name. Please help me how to solve it.
To set the Sequelize findAll sort order in Node. js, we can set the order property. const getStaticCompanies = () => { return Company. findAll({ where: { //... }, order: [ ['id', 'DESC'], ['name', 'ASC'], ], attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'] }); };
To add an ORDER BY clause to the Sequelize query methods, you need to specify the order option inside the query methods you used for retrieving data from your database. Now you are tasked with retrieving the data from the table, ordering the result with the following rules: Sort by population column in descending order.
The Sequelize findAll() method is used to query data from your SQL table to your JavaScript application. The method will return your table rows as an array of objects. The findAll() method can be called from a Model that represents the table in your database.
In sequelize you can easily add order by clauses.
exports.getStaticCompanies = function () { return Company.findAll({ where: { id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680] }, // Add order conditions here.... order: [ ['id', 'DESC'], ['name', 'ASC'], ], attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'] }); };
See how I've added the order
array of objects?
order: [ ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order ],
Edit:
You might have to order the objects once they've been recieved inside the .then()
promise. Checkout this question about ordering an array of objects based on a custom order:
How do I sort an array of objects based on the ordering of another array?
If you want to sort data either in Ascending or Descending order based on particular column, using sequlize js
, use the order
method of sequlize
as follows
// Will order the specified column by descending order order: sequelize.literal('column_name order') e.g. order: sequelize.literal('timestamp DESC')
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