node.jssequelize.jssequelize-cli

How to get all records from the last 7 days sequelize


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


Solution

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

    try

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

    or

    import moment from 'moment'