how to update the field 'updated_at' of a sequelize model without modifiyng any attributes

11,793

To update an instance value, you can use instance.set(key, value, [options]).

myInstance.set('updatedAt', new Date());
myInstance.save().then(function() {
  // my nice callback stuff
});

The sequelize docs have a good example of doing an update query if you don't have an instance:

Post.update({
  updatedAt: null,
}, {
  where: {
    deletedAt: {
      $ne: null
    }
  }
});
Share:
11,793
naike
Author by

naike

Updated on June 12, 2022

Comments

  • naike
    naike almost 2 years

    I'm using sequelize 2.0.0 with PostgreSQL. I would like to know if it's possible to update the field 'updated_at' of a model with one method. If yes, how can I achieve that?

    For instance, in others frameworks, like Laravel, you have model.touch() to automatically update the 'updated_at' of a model.

    I've already tried to use model.save() but as the sequelize doc says, calling this method without attributes does nothing. Also, in the doc, I didn't find anything that allow me to do what I need to do simply.

    Thanks in advance for help.

    Edit: To give an example of what I'm trying to achieved, I've already had an instance of my model: Model.findById(1).then(function(myInstance){ [...] myInstance.update() //here, I didn't change any attributes of myInstance and I would like to update the field udpated_at without doing another query. [...] }): The question is : How can I update the field updated_at of my previous instance with one method?

  • naike
    naike over 8 years
    I would like to avoid this query because I've already had an instance of my class. Now I'm trying to do the update with this instance.
  • klmdb
    klmdb over 8 years
    The provided instance method doesn't seem to be working for me.
  • Matt Holtzman
    Matt Holtzman over 8 years
    Since you referenced 'updated_at' above instead of 'updatedAt', perhaps you need to reference the correct field. This could also (confusingly be the case) if you have your configuration set to { timestamps: true, updatedAt: 'updated_at' } or something similar. You need to reference the underscored version, not the camel case version.
  • Marius
    Marius over 3 years
    ow can we set updatedAt to the database current timestamp? In postgres: 'updated_at = now()' We don't want to set the date from nodejs (slightly different), also don't want to use db triggers.
  • adamsfamily
    adamsfamily almost 3 years
    I don't know about PostgreSQL but the following works in MySQL for me: myInstace.changed('updatedAt', true); myInstance.save();