Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort sequelize.js query by date

Post   .findAll({where: {tag: 'news'}, limit: 10})   .success(function(result) { ... }) 

How to insert the condition of sorting by date in my query with not using sequelize.query like

.findAll({ limit: 10, sort: [updatedAt, descending]}) 
like image 699
khex Avatar asked Dec 21 '13 11:12

khex


People also ask

How do I sort data in Sequelize?

You need to specify the column name and the order of the sort as a single Array unit inside the order array. If you only need to order by one column, you still need to put the ordering array inside the order array as follows: Cities. findAll({ order: [["population", "DESC"]], }).

How do you get all records by Created date today in Sequelize?

const TODAY = new Date(); const SUM = await OrdersModel. sum('price', { where: { created: Sequelize. DATE(TODAY), }, }); console. log(SUM);

What is findByPk?

findByPk ​ The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {

How do you query in Sequelize?

Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );


2 Answers

@dankohn is correct and that will work but it is safer to use the following:

Post.findAll({ limit: 10, order: [['updatedAt', 'DESC']]}); 

as this

will escape updatedAt and validate DESC against a list of valid direction parameters

like image 89
Clarkie Avatar answered Sep 19 '22 11:09

Clarkie


Here's the syntax:

Post.findAll({ limit: 10, order: '"updatedAt" DESC' }) 

Here are more examples from the official documentation.

like image 30
Dan Kohn Avatar answered Sep 23 '22 11:09

Dan Kohn