How to update using Sequelize using the "NOW ()" function in a timestamp?

I am trying to do something like the following:

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

Obviously, this does not work because it is simply passed as a string. I want to avoid passing the constructed node timestamp, because later I compare it with another field “ON UPDATE CURRENT_TIMESTAMP”, and the database and source can work at different points in time.

Am I the only option to just do a database procedure and call it?

+6
source share
2 answers

You can use Sequelize.fn to wrap it accordingly:

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

Here is a complete 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); }); 

It creates

 UPDATE "models" SET "syncedAt"=NOW(),"updatedAt"='2015-02-09 18:05:28.989 +00:00' WHERE "id"=1 
+14
source

It is worth mentioning (for people coming here through a search) that NOW () is not standard and does not work on the SQL server - so do not do this if you care about portability.

 sequelize.literal('CURRENT_TIMESTAMP') 

may work better

+7
source

Source: https://habr.com/ru/post/982217/


All Articles