Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update with Sequelize with 'NOW()' on a timestamp?

I'm trying to do something like the following:

model.updateAttributes({syncedAt: 'NOW()'}); 

Obviously, that doesn't work because it just gets passed as a string. I want to avoid passing a node constructed timestamp, because later I compare it to another 'ON UPDATE CURRENT_TIMESTAMP' field and the database and source could be running different times.

Is my only option to just make a database procedure and call that?

like image 641
Ben Avatar asked Feb 09 '15 16:02

Ben


2 Answers

You can use Sequelize.fn to wrap it appropriately:

instance.updateAttributes({syncedAt: sequelize.fn('NOW')}); 

Here's a full working example:

'use strict';  var Sequelize = require('sequelize'); var sequelize = new Sequelize(/*database*/'test', /*username*/'test', /*password*/'test',     {host: 'localhost', dialect: 'postgres'});  var model = sequelize.define('model', {     syncedAt: {type: Sequelize.DATE} });  sequelize.sync({force: true})     .then(function () {         return model.create({});     })     .then(function () {         return model.find({});     })     .then(function(instance){         return instance.updateAttributes({syncedAt: sequelize.fn('NOW')});     })     .then(function () {         process.exit(0);     })     .catch(function(err){         console.log('Caught error! ' + err);     }); 

That produces

UPDATE "models" SET "syncedAt"=NOW(),"updatedAt"='2015-02-09 18:05:28.989 +00:00' WHERE "id"=1 
like image 78
srlm Avatar answered Oct 03 '22 05:10

srlm


Worth mentioning (for people coming here via search) that NOW() isn't standard and doesn't work on SQL server - so don't do this if you care about portability.

sequelize.literal('CURRENT_TIMESTAMP') 

may work better

like image 29
user2643726 Avatar answered Oct 03 '22 04:10

user2643726