Quoc Vu bio photo

Quoc Vu

Son, husband, father, and code addict.

Email LinkedIn Github

This post shows you how add timestamps such as created_at and updated_at to all your models in Loopback.

A Base Model

First define a base model that all models will inherit from. You can use the model generator, or put add these 2 files in your project/

common/models/base-model.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
  "name": "BaseModel",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "createdAt": {
      "type": "date",
      "defaultFn": "now",
      "required": true
    },
    "updatedAt": {
      "type": "date",
      "defaultFn": "now",
      "required": true
    },
    "deletedAt": {
      "type": "date"
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": []
}

We simply define 3 date fields createdAt, updatedAt, and deletedAt (if you wish to implement a soft delete).

common/models/base-model.js

1
2
3
4
5
6
7
8
9
10
11
12
module.exports = function(BaseModel) {

  BaseModel.beforeCreate = function (next, model) {
    model.createdAt = Date.now();
    next();
  };

  BaseModel.beforeUpdate = function (next, model) {
    model.updatedAt = Date.now();
    next();
  };
};

We define the behavior before an instance of the model is created and updated.

The everytime, we add a new model, we use BaseModel as the base model. It’s that simple.

Note: This method is only supported if you use the in memory database, MySQL, or MongoDB connectors.