smileham smileham - 3 months ago 18
Javascript Question

Sails.js model updatedAt (updated_at) not auto updating

Expected Behavior:

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

updated_at
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
updated_at
instead of
updatedAt
. It should still have the same functionality I would assume.


Actual Behavior:

The model successfully updates, but it does not update the
updated_at
field.

Code Run:

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


Questions:


  • 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: https://github.com/balderdashy/sails/issues/3821

See my answer below for more info.

Answer

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:

    updated_at:{
        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();
model.update(primary,data)....

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:

attributes:{
    //stuffs
},
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.

Comments