Blaher Blaher - 23 days ago 22
Node.js Question

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?

Answer

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