Macro Programming Code on Screent
Markus Spiske via Pexels
Home / Sequelize throws SequelizeDatabaseError when using JavaScript Dates
Node JS

Sequelize throws SequelizeDatabaseError when using JavaScript Dates

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.

From 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"

Advertisement Begins

Advertisement End


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)
})

MY MISSION

This blog started nearly 10 years ago to help me document my technical adventures in home automation and various side projects. Since then, my audience has grown significantly thanks to readers like you.

While blog content can be incredibly valuable to visitors, it’s difficult for bloggers to capture any of that value – and we still have to work for a living too. There are many ways to support my efforts should you choose to do so:

Consider joining my newsletter or shouting a coffee to help with research, drafting, crafting and publishing of new content or the costs of web hosting.

It would mean the world if gave my Android App a go or left a 5-star review on Google Play. You may also participate in feature voting to shape the apps future.

Alternatively, leave the gift of feedback, visit my Etsy Store or share a post you liked with someone who may be interested. All helps spread the word.

BTC network: 32jWFfkMQQ6o4dJMpiWVdZzSwjRsSUMCk6

Continue your adventure here

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

DON’T MISS OUT!
Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.
close-link