Ben Young
Ben Young

Reputation: 577

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?

Upvotes: 42

Views: 73917

Answers (3)

Arthur Mastropietro
Arthur Mastropietro

Reputation: 703

you can use: sequelize.literal('CURRENT_TIMESTAMP'). Example:

await PurchaseModel.update( {purchase_date : sequelize.literal('CURRENT_TIMESTAMP') }, { where: {id: purchaseId} } );

Upvotes: 3

user2643726
user2643726

Reputation: 471

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

Upvotes: 37

srlm
srlm

Reputation: 3216

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

Upvotes: 55

Related Questions