Sequelize where expression with date

I use sequelize as my backend ORM. Now I want to do some date operations.

Details I want to get all the data where the date is now and 7 days ago.

The problem is that the documentation does not indicate what operations you can perform on Datatypes.DATE

Can someone point me in the right direction?

+23
source share
3 answers

Like Moldova, you can use $gt , $lt , $gte or $lte with a date:

 model.findAll({ where: { start_datetime: { $gte: moment().subtract(7, 'days').toDate() } } }) 
+31
source

I had to import operator characters from sequelize and use it like that.

 const { Op } = require('sequelize') model.findAll({ where: { start_datetime: { [Op.gte]: moment().subtract(7, 'days').toDate() } } }) 

According to the documents, for security reasons this is considered best practice.

See http://docs.sequelizejs.com/manual/tutorial/querying.html for more information.

Using Sequelize without aliases improves security. Some frameworks automatically analyze user input in js objects, and if you are unable to sanitize the input, you can probably enter the object using string operators for Sequelize.

(...)

For greater security, it is strongly recommended that you use Sequelize.Op and not depend on any string alias. You can limit the alias your application will need by setting the operatorAliases option, remember to sanitize user input, especially when you pass them directly to Sequelize methods.

+26
source

You can also use Sequelize.literal() to perform date manipulation in SQL.

The following code works with Postgres, but I'm sure something similar can be done on other systems:

 model.findAll({ where: { start_datetime: { $gte: Sequelize.literal('NOW() - INTERVAL "7d"'), } } }) 
0
source

Source: https://habr.com/ru/post/985679/


All Articles