In LoopBack 4 currently there is no feature to auto update created and modified properties like LoopBack 3. But we can do this in Loopback 4 with following way.
You have to create “created” and “modified” properties key in your model file with default value function which is current timestamp. And for update “modified” key of collection, update its value with current timestamp before saving it.
In Model File:
@property({
type: 'date',
default: () => new Date()
})
created ? : string;
@property({
type: 'date',
default: () => new Date()
})
modified ? : string;
In Repository File:
constructor(
@inject('datasources.db') dataSource: DbDataSource,
) {
super(User, dataSource);
(this.modelClass as any).observe('persist', async (ctx: any) => {
ctx.data.modified = new Date();
});
}
This way always “created” and “modified” keys will have default value on model creation time. And “modified” key value will be always updated with current timestamp on updating collection of Model.
You can use this trick until LoopBack provide a better solution for it.
You may also like other Programming Tutorials: Programming