How to get all records from the last 7 days sequelize
Asked Answered
S

3

8

I am trying to get all records from a mysql Database with sequelize and I have tried following approaches:

shops.findAndCountAll({
  where: {
    createdAt: {
      [Op.gte]: moment().subtract(7, 'days').toDate()
    }
  }
})

and when I use this, I get the error: ReferenceError: moment is not defined

So I tried this approach:

shops.findAndCountAll({
  where: {
    createdAt: {
      [Op.gte]: Sequelize.literal('NOW() - INTERVAL "7d"'),
    }
  }
})

But I get the following error

code: 'ER_PARSE_ERROR',
    errno: 1064,
    sqlState: '42000',
    sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to 

your MySQL server version for the right syntax to use near '' at line 1",
        sql: "SELECT count(*) AS `count` FROM `shop` AS `shops` WHERE `shops`.`createdAt` >= NOW() - INTERVAL '7d';"
      },
      sql: "SELECT count(*) AS `count` FROM `shop` AS `shops` WHERE `shops`.`createdAt` >= NOW() - INTERVAL '7d';"
    }

How can I fix this issue. I do not mind which of the approaches I use, as long as I get it to work.

Thank you in advance

Servetnick answered 22/2, 2020 at 18:40 Comment(1)
import moment for the first error? also you are adding to the stringPaige
D
10

You are not importing moment ; therefore moment is not defined.

try

const moment = require('moment') //<es6

or

import moment from 'moment' 
Daystar answered 22/2, 2020 at 18:49 Comment(0)
S
2

Using DATE_ADD() or DATE_SUB()

SELECT * FROM Table_Name
WHERE connect_time >= DATE_ADD(CURDATE(),INTERVAL -7 DAY);

or

SELECT * FROM Table_Name
WHERE connect_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY);

Without those functions, you can also do

SELECT * FROM Table_Name
WHERE connect_time >= (CURDATE() + INTERVAL -7 DAY);

or

SELECT * FROM Table_Name
WHERE connect_time >= (CURDATE() - INTERVAL 7 DAY);
Sausauce answered 19/2, 2021 at 5:23 Comment(0)
P
-1

You could have get the result in the second approach by following this

const dayCount = '7d';

shops.findAndCountAll({
  where: {
    createdAt: {
      [Op.gte]: Sequelize.literal(`NOW() - INTERVAL '${dayCount}'`),
    }
  }
})

you can reuse this logic for any date ranges by changing dayCount param

Picked answered 19/9, 2023 at 2:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.