Skip to content
Advertisement

Sequelize Where statement with date

I am using Sequelize as my backend ORM. Now I wish to do some WHERE operations on a Date.

More specifically, I want to get all data where a date is between now and 7 days ago.

The problem is that the documentation does not specify which operations you can do on Datatypes.DATE

Can anyone point me in the right direction?

Advertisement

Answer

Just like Molda says, you can use $gt, $lt, $gte or $lte with a date:

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

If you’re using v5 of Sequelize, you’ve to include Op because the key was moved into Symbol

const { Op } = require('sequelize')

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

See more sequelize documentation here

Advertisement