Auto-migrations settings
autoCreatedAt and autoUpdatedAt
Summary
In Sails.js, the autoCreatedAt
and autoUpdatedAt
settings automate timestamp management for records. These settings ensure:
autoCreatedAt
: Adds a timestamp when a record is created (e.g., viaModel.create()
).autoUpdatedAt
: Updates the timestamp whenever a record is modified (e.g., viaModel.update()
).
These fields are typically defined inconfig/models.js
but can be customized or renamed per model. The actual attribute names (e.g.,createdAt
,lastModified
) are flexible, but the settings themselves (autoCreatedAt
/autoUpdatedAt
) trigger the automation.
Transcript
Kelvin Omereshone (00:00):
Let’s explore another auto-migration setting in Sails.js: autoCreatedAt
and autoUpdatedAt
.
If you look at the default model configuration in config/models.js
, you’ll see attributes like:
javascript
Copy
createdAt: { type: 'number', autoCreatedAt: true },
updatedAt: { type: 'number', autoUpdatedAt: true }
Here’s what these settings do:
autoCreatedAt
: When a new record is created (e.g., usingModel.create()
), Sails automatically populates this field with the current timestamp.autoUpdatedAt
: When a record is updated (e.g., usingModel.update()
), Sails updates this field to the current timestamp.
For example, if you rename createdAt
to registeredOn
but keep autoCreatedAt: true
:
// In a model definition
attributes: {
registeredOn: { type: 'number', autoCreatedAt: true },
lastModified: { type: 'number', autoUpdatedAt: true }
}
The timestamps will still work—the attribute name is irrelevant as long as the autoCreatedAt
/autoUpdatedAt
flag is set.
Key Takeaways:
Use
autoCreatedAt
to track record creation time.Use
autoUpdatedAt
to track record modification time.The attribute names (e.g.,
createdAt
,lastModified
) are customizable.Configure these globally in
config/models.js
or override per model.By default, timestamps use epoch numbers (
type: 'number'
), but you can usetype: 'ref'
for JavaScriptDate
objects.
Full Course
USD