Page Contents

Overview

When defining a model in LoopBack 4, property types are the important part. No matter whether it is for defining properties with decorator @property or defining a model at runtime, you may want to specify the types in the definition. The following is a typical property definition:

Defining a property with the decorator

@property({   type: 'string',   require: true,   // other fields }) userName: String; 

Defining a model at runtime

const UserDef = new ModelDefinition('User')   .addProperty('id', {type: 'number', id: true})   .addProperty('userName', {type: 'string'}); 

The following table summarizes LoopBack types.

Type Description Example
any Any type, including array, object, Date, or GeoPoint Any of: true, 123, "foo", [ "one", 2, true ]
array

JSON array

See Array types below.

[ "one", 2, true ]
Boolean JSON Boolean true
buffer Node.js Buffer object
new Buffer(42);
date JavaScript Date object

new Date("December 17, 2003 03:24:00");

GeoPoint

LoopBack GeoPoint object

new GeoPoint({lat: 10.32424, lng: 5.84978});
Date

LoopBack DateString object

"2000-01-01T00:00:00.000Z"

"2000-01-01"

"2000-01-01 12:00:00"

null JSON null null
number JSON number

3.1415

Object

JSON object or any type

See Object types below.

{ "userName": "John89", "age": 25, "vip": false}
String JSON string "LoopBack"

In general, a property will have undefined value if no explicit or default value is provided.

Array types

The following are examples of how you can define array type properties:

  @property({     type: 'array',     itemType: 'string',     length: 20,   })   strAry?: string[]; // e.g ['can', 'only', 'contain', 'strings']    @property({     type: 'array',     itemType: 'number',   })   numAry?: number[]; // e.g [42, 998, 1]    @property({     type: 'array',     itemType: 'any',   })   anyAry?: any[]; // e.g ['LoopBack', 4, true]    @property({     type: 'array',     itemType: 'object',   })   ObjAry?: object[]; // e.g [{'Nodejs': 'LoopBack'}] 

Object types

Use the Object type when you need to be able to accept values of different types, for example a string or an array.

A model often has properties that consist of other properties. For example, the user model can have an address property that is in type Address, which has properties streetcitystate, and zipCode:

@model() export class Address extends Entity {   @property({     type: 'number',   })   id: number;    // street, city, state, zipCode proper definitions .. }  @model() export class User extends Entity {   // other props    @property({     type: 'object',   })   address: Address; } 

The value of the address is the definition of the Address type.