Sequelize throws SequelizeDatabaseError when using JavaScript Dates

How to get over this problem.

I ran into this problem where Sequelize would not accept the date generated by Javascript’s new Date() function when using greater than operator ($gt, $lt).

Sequelize Model Query

const time = new Date(new Date() - 5 * 60 * 1000) // 5 min ago
scanService.Model.findOrCreate({
  where: {
    code: barcode.barcode,
    createdAt: { [Op.gt]: time }
  },
  defaults: {code: barcode.barcode}
}).then(([scan, created])=> {
  console.log(scan)
}).catch(e=>{
  console.log(e)
})

This use case is specifically mentioned in the documentation. Sequelize Documentation

{
  createdAt: {
    [Op.lt]: new Date(),
    [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
  }
}

Error messages

SequelizeDatabaseError: invalid input syntax for type timestamp with time zone: "Invalid date"

Solution

When using these operators, the where property must be an array and not an object!

This is not well documented and the question popped up in multiple Stack Overflow posts.

Sequelize Model Query (with Fix)

return scanService.Model.findOrCreate({
  where: [{
    code: barcode.barcode,
    createdAt: { [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000) }
  }],
  defaults: {code: barcode.barcode}
}).then(([scan, created])=> {
  console.log(scan)
}).catch(e=>{
  console.log(e)
})