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