smileham smileham - 10 months ago 53
Javascript Question

Sails.js model updatedAt (updated_at) not auto updating

Expected Behavior:

After successfully updating a record using .update(), the record's

field should auto-update to the current time.

Note: I changed the autoUpdatedAt setting (also mentioned here) using
autoUpdatedAt: 'updated_at'
in config.models so the field is titled
instead of
. It should still have the same functionality I would assume.

Actual Behavior:

The model successfully updates, but it does not update the

Code Run:

model.update(primary, data)
.then(function updateCB(updated){
// error handling
sails.log('Updated successfully');


  • Why is this?

  • How do I fix this?

Result: Issue for Sails

I was able to reproduce it on a new project, so it looks like it's a problem with sails. Issue link:

See my answer below for more info.


I can't answer the 'why' I tried the same thing and ran into the same issue. As for how to fix it -

I made it an attribute in my model file for any models I wanted it on and filled it out like so:

        type: 'datetime',
        defaultsTo: function(){return new Date();}

With the column in my DB (mysql in this case) being set to NOT NULL and DATETIME and set to update CURRENT_TIMESTAMP on UPDATE.

You can also put this in code if you don't have access to your db, just before your update call:

data.updated_at = new Date();

That will accomplish the same thing.

This has been the simplest work around I've been able to come up with.

I got thinking about this and I came up with a third option, a model method written like so:

beforeUpdate: function(obj, next){
    obj.updated_at = new Date();
    return next(null, obj);

The null in the first position is because as far as I can tell Sails expects an error object throughout the call chain so if I passed nothing along then the whole thing crapped out.