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 |
|
| GeoPoint |
LoopBack GeoPoint object |
new GeoPoint({lat: 10.32424, lng: 5.84978});
|
| Date |
LoopBack DateString object |
|
| null | JSON null | null |
| number | JSON number |
|
| 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.
Tip: The type name is case-insensitive; so for example you can use either “Number” or “number”.
Note:
GeoPoint is not supported. See GitHub issue
#1981
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 street, city, state, 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.
Important:
The User model has to reference the Address model.