Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query by Date Range for a column field in Sequelize

I'm trying to query a database with Sequelize to get items that were created between a certain date range. I used the $between operator but I don't seem to be getting anything.

{ where: {"createdAt":{"$between":["2018-03-31T21:00:00.000Z","2018-05-30T05:23:59.007Z"]}} }

Can anyone help with how I can achieve this?

like image 262
proton Avatar asked May 30 '18 05:05

proton


People also ask

Is there a simple way to make Sequelize return It's date/time fields in a particular format?

You can, use the Sequelize fn method. From the API Reference, the fn function will help create an object representing a SQL function in your query.

How do I use Groupby Sequelize?

In Sequelize, you can add the group option in your query method findAll() to add the GROUP BY clause to the generated SQL query. Now you want to select all firstName values and group any duplicate values of the column. Here's the code for calling the findAll() method on the model: const users = await User.


2 Answers

I also had the same problem, I was getting empty array in response. The problem got fixed using :

const Op = Sequelize.Op;

and then using [Op.between] as shown below:

where: {
  createdAt: {
    [Op.between]: ["2018-07-08T14:06:48.000Z", "2019-10-08T22:33:54.000Z"]
  }
}

Hope it helps :)

like image 92
Mohit Avatar answered Oct 29 '22 04:10

Mohit


$between syntax seems to be right. There are no issues with the way you used. I tried to replicate with the following query

  model.findAll({
    where: {
      created_at: { 
        "$between": ["2018-03-31T21:00:00.000Z","2018-05-30T05:23:59.007Z"]
      }
    }
  })

The only change is, I use created_at instead of createdAt. Make sure that your column name is right. If it is not, it should have thrown SequelizeDatabaseError. Look for it.

If everything else is right, then you might not be having data in that date range :)

like image 39
BinaryMee Avatar answered Oct 29 '22 04:10

BinaryMee