LoopBack models can manipulate data via the DataSource object.
Attaching a DataSource
to a Model
adds instance methods and static methods to the Model
.
Define a data source to persist model data.
To create a DataSource programmatically, call createDataSource()
on the LoopBack object; for example:
var oracle = loopback.createDataSource({
connector: 'oracle',
host: '111.22.333.44',
database: 'MYDB',
username: 'username',
password: 'password'
});
All classes in single dataSource share same the connector type and one database connection.
For example, the following creates a DataSource, and waits for a connection callback.
var dataSource = new DataSource('mysql', { database: 'myapp_test' });
dataSource.define(...);
dataSource.on('connected', function () {
// work with database
});
Name | Type | Description |
---|---|---|
[name] |
String
|
Optional name for datasource. |
settings |
Object
|
Database-specific settings to establish connection (settings depend on specific connector). The table below lists a typical set for a relational database. |
Name | Type | Description |
---|---|---|
connector |
String
|
Database connector to use. For any supported connector, can be any of:
|
host |
String
|
Database server host name. |
port |
String
|
Database server port number. |
username |
String
|
Database user name. |
password |
String
|
Database password. |
database |
String
|
Name of the database to use. |
debug |
Boolean
|
Display debugging information. Default is false. The constructor allows the following styles:
|
Define readonly property on object
Name | Type | Description |
---|---|---|
obj |
Object
|
The property owner |
key |
String
|
The property name |
value |
Mixed
|
The default value |
Define a hidden property It is an utility to define a property to the Object with info flags
Name | Type | Description |
---|---|---|
obj |
Object
|
The property owner |
key |
String
|
The property name |
value |
Mixed
|
The default value |
Attach an existing model to a data source. This will mixin all of the data access object functions (DAO) into your modelClass definition.
Name | Type | Description |
---|---|---|
modelClass |
Function
|
The model constructor that will be enhanced by DAO mixins. |
Drop schema objects such as tables, indexes, views, triggers, etc that correspond
to model definitions attached to this DataSource instance, specified by the models
parameter.
WARNING: In many situations, this will destroy data! autoupdate()
will attempt to preserve
data while updating the schema on your target DataSource, but this is not guaranteed to be safe.
Please check the documentation for your specific connector(s) for a detailed breakdown of behaviors for automigrate!
Name | Type | Description |
---|---|---|
[models] |
String or Array.<String>
|
Model(s) to migrate. If not present, apply to all models. |
[callback] |
Function
|
Callback function. Optional. |
Update existing database tables. This method applies only to database connectors.
WARNING: autoupdate()
will attempt to preserve data while updating the
schema on your target DataSource, but this is not guaranteed to be safe.
Please check the documentation for your specific connector(s) for a detailed breakdown of behaviors for automigrate!*
Name | Type | Description |
---|---|---|
[models] |
String or Array.<String>
|
Model(s) to migrate. If not present, apply to all models. |
[cb] |
Function
|
The callback function |
Introspect a JSON object and build a model class
Name | Type | Description |
---|---|---|
name |
String
|
Name of the model |
json |
Object
|
The json object representing a model instance |
options |
Object
|
Options |
Name | Type | Description |
---|---|---|
result |
Model
|
A Model class |
Return column metadata for specified modelName and propertyName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
propertyName |
String
|
The property name |
Name | Type | Description |
---|---|---|
result |
Object
|
column metadata |
Return column name for specified modelName and propertyName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
propertyName |
String
|
The property name |
Name | Type | Description |
---|---|---|
result |
String
|
columnName The column name. |
Return column names for specified modelName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
column names |
Connect to the data source. If no callback is provided, it will return a Promise. Emits the 'connect' event.
Name | Type | Description |
---|---|---|
callback |
|
Name | Type | Description |
---|---|---|
result |
Promise
|
Define a model class. Returns newly created model object. The first (String) argument specifying the model name is required. You can provide one or two JSON object arguments, to provide configuration options. See Model definition reference for details.
Simple example:
var User = dataSource.createModel('User', {
email: String,
password: String,
birthDate: Date,
activated: Boolean
});
More advanced example
var User = dataSource.createModel('User', {
email: { type: String, limit: 150, index: true },
password: { type: String, limit: 50 },
birthDate: Date,
registrationDate: {type: Date, default: function () { return new Date }},
activated: { type: Boolean, default: false }
});
You can also define an ACL when you create a new data source with the DataSource.create()
method. For example:
var Customer = ds.createModel('Customer', {
name: {
type: String,
acls: [
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.WRITE, permission: ACL.DENY},
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
]
}
}, {
acls: [
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
]
});
Name | Type | Description |
---|---|---|
className |
String
|
Name of the model to create. |
properties |
Object
|
Hash of model properties in format |
properties |
Object
|
Other configuration options. This corresponds to the options key in the config object. |
settings |
Object
|
A settings object that would typically be used for Model objects. |
Define foreign key to another model
Name | Type | Description |
---|---|---|
className |
String
|
The model name that owns the key |
key |
String
|
Name of key field |
foreignClassName |
String
|
The foreign model name |
pkName |
String
|
(optional) primary key used for foreignKey |
Define an operation to the data source
Name | Type | Description |
---|---|---|
name |
String
|
The operation name |
options |
Object
|
The options |
fn |
Function
|
The function |
Define a property with name prop
on a target model
. See
Properties for more information
regarding valid options for params
.
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
prop |
String
|
Name of property |
params |
Property
|
Property settings |
Disable remote access to a data source operation. Each connector has its own set of set enabled
and disabled operations. To list the operations, call dataSource.operations()
.
var oracle = loopback.createDataSource({
connector: require('loopback-connector-oracle'),
host: '...',
...
});
oracle.disableRemote('destroyAll');
Notes:
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Close connection to the DataSource.
Name | Type | Description |
---|---|---|
[cb] |
Function
|
The callback function. Optional. |
Discover and build models from the specified owner/modelName.
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name. |
[options] |
Object
|
Options; see below. |
[cb] |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
Database owner or schema name. |
relations |
Boolean
|
True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean
|
True if all owners are included; false otherwise. |
views |
Boolean
|
True if views are included; false otherwise. |
Name | Type | Description |
---|---|---|
result |
Promise
|
A Promise object that resolves with a map of model constructors, keyed by model name |
Discover and build models from the given owner/modelName synchronously.
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name. |
[options] |
Object
|
Options; see below. |
modelName |
String
|
The model name |
[options] |
Object
|
The options |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
Database owner or schema name. |
relations |
Boolean
|
True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean
|
True if all owners are included; false otherwise. |
views |
Boolean
|
True if views are included; false otherwise. |
Name | Type | Description |
---|---|---|
result |
Object
|
A map of model constructors, keyed by model name |
Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table), ordered by fkTableOwner, fkTableName, and keySeq.
Callback function return value is an object that can have the following properties:
Key | Type | Description |
---|---|---|
fkOwner | String | Foreign key table schema (may be null) |
fkName | String | Foreign key name (may be null) |
fkTableName | String | Foreign key table name |
fkColumnName | String | Foreign key column name |
keySeq | Number | Sequence number within a foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key). |
pkOwner | String | Primary key table schema being imported (may be null) |
pkName | String | Primary key name (may be null) |
pkTableName | String | Primary key table name being imported |
pkColumnName | String | Primary key column name being imported |
See Relations for more | ||
information. |
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
The database owner or schema |
Name | Type | Description |
---|---|---|
result |
Promise
|
A Promise with an array of exported foreign key relations. |
The synchronous version of discoverExportedForeignKeys
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover foreign keys for a given owner/modelName
Callback function return value is an object that can have the following properties:
Key | Type | Description |
---|---|---|
fkOwner | String | Foreign key table schema (may be null) |
fkName | String | Foreign key name (may be null) |
fkTableName | String | Foreign key table name |
fkColumnName | String | Foreign key column name |
keySeq | Number | Sequence number within a foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key). |
pkOwner | String | Primary key table schema being imported (may be null) |
pkName | String | Primary key name (may be null) |
pkTableName | String | Primary key table name being imported |
pkColumnName | String | Primary key column name being imported |
See Relations for more | ||
information. |
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
The database owner or schema |
Name | Type | Description |
---|---|---|
result |
Promise
|
A Promise with an array of foreign key relations. |
The synchronous version of discoverForeignKeys
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover existing database tables. This method returns an array of model objects, including {type, name, onwer}
Name | Type | Description |
---|---|---|
options |
Object
|
Discovery options. See below. |
Callback |
Function
|
function. Optional. |
Name | Type | Description |
---|---|---|
owner/schema |
String
|
The owner or schema to discover from. |
all |
Boolean
|
If true, discover all models; if false, discover only models owned by the current user. |
views |
Boolean
|
If true, include views; if false, only tables. |
limit |
Number
|
Page size |
offset |
Number
|
Starting index |
Name | Type | Description |
---|---|---|
result |
Array.<ModelDefinition>
|
The synchronous version of discoverModelDefinitions.
Name | Type | Description |
---|---|---|
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
all |
Boolean
|
If true, discover all models; if false, discover only models owned by the current user. |
views |
Boolean
|
If true, nclude views; if false, only tables. |
limit |
Number
|
Page size |
offset |
Number
|
Starting index |
Name | Type | Description |
---|---|---|
result |
Array.<ModelDefinition>
|
Discover properties for a given model.
Callback function return value is an object that can have the following properties:
Key | Type | Description |
---|---|---|
owner | String | Database owner or schema |
tableName | String | Table/view name |
columnName | String | Column name |
dataType | String | Data type |
dataLength | Number | Data length |
dataPrecision | Number | Numeric data precision |
dataScale | Number | Numeric data scale |
nullable | Boolean | If true, then the data can be null |
See Properties for more | ||
details on the Property return type. |
Name | Type | Description |
---|---|---|
modelName |
String
|
The table/view name |
options |
Object
|
The options |
cb |
Function
|
Callback function. Optional |
cb
|
Name | Type | Description |
---|---|---|
owner|schema |
String
|
The database owner or schema |
Name | Type | Description |
---|---|---|
result |
Promise
|
A promise that returns an array of Properties (Property[]) |
The synchronous version of discoverModelProperties
Name | Type | Description |
---|---|---|
modelName |
String
|
The table/view name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover primary keys for a given owner/modelName. Callback function return value is an object that can have the following properties:
Key | Type | Description |
---|---|---|
owner | String | Table schema or owner (may be null). Owner defaults to current user. |
tableName | String | Table name |
columnName | String | Column name |
keySeq | Number | Sequence number within primary key (1 indicates the first column in the primary key; 2 indicates the second column in the primary key). |
pkName | String | Primary key name (may be null) |
See ID Properties for more | ||
information. |
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
The database owner or schema |
Name | Type | Description |
---|---|---|
result |
Promise
|
A promise with an array of Primary Keys (Property[]) |
The synchronous version of discoverPrimaryKeys
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
The database owner or schema |
Name | Type | Description |
---|---|---|
result |
|
Discover one schema from the given model without following the relations. Example schema from oracle connector:*
{
"name": "Product",
"options": {
"idInjection": false,
"oracle": {
"schema": "BLACKPOOL",
"table": "PRODUCT"
}
},
"properties": {
"id": {
"type": "String",
"required": true,
"length": 20,
"id": 1,
"oracle": {
"columnName": "ID",
"dataType": "VARCHAR2",
"dataLength": 20,
"nullable": "N"
}
},
"name": {
"type": "String",
"required": false,
"length": 64,
"oracle": {
"columnName": "NAME",
"dataType": "VARCHAR2",
"dataLength": 64,
"nullable": "Y"
}
},
...
"fireModes": {
"type": "String",
"required": false,
"length": 64,
"oracle": {
"columnName": "FIRE_MODES",
"dataType": "VARCHAR2",
"dataLength": 64,
"nullable": "Y"
}
}
}
}
Name | Type | Description |
---|---|---|
tableName |
String
|
The name of the table to discover. |
[options] |
Object
|
An options object typically used for Relations. See Relations for more information. |
[cb] |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
result |
Promise
|
A promise object that resolves to a single schema. |
Discover schema from a given tableName/viewName.
Name | Type | Description |
---|---|---|
tableName |
String
|
The table name. |
[options] |
Object
|
Options; see below. |
[cb] |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
Database owner or schema name. |
relations |
Boolean
|
True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean
|
True if all owners are included; false otherwise. |
views |
Boolean
|
True if views are included; false otherwise. |
Name | Type | Description |
---|---|---|
result |
Promise
|
A promise object that resolves to an array of schemas. |
Discover schema from a given table/view synchronously
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
Options; see below. |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
Database owner or schema name. |
relations |
Boolean
|
True if relations (primary key/foreign key) are navigated; false otherwise. |
all |
Boolean
|
True if all owners are included; false otherwise. |
views |
Boolean
|
True if views are included; false otherwise. |
Name | Type | Description |
---|---|---|
result |
Array.<Object>
|
An array of schema definition objects. |
Enable remote access to a data source operation. Each connector has its own set of set
remotely enabled and disabled operations. To list the operations, call dataSource.operations()
.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Freeze dataSource. Behavior depends on connector To continuously add artifacts to datasource until it is frozen, but it is not really used in loopback.
See ModelBuilder.getModel for details.
See ModelBuilder.getModelDefinition See ModelBuilder.getModelDefinition for details.
Get an operation's metadata.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Get the data source types collection.
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
The data source type array. For example, ['db', 'nosql', 'mongodb'] would be represent a datasource of type 'db', with a subtype of 'nosql', and would use the 'mongodb' connector. Alternatively, ['rest'] would be a different type altogether, and would have no subtype. |
Find the ID column name
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
String
|
columnName for ID |
Find the ID property name
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
String
|
property name for ID |
Find the ID property names sorted by the index
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
property names for IDs |
Find the id property definition
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Object
|
The id property definition |
Check whether or not migrations are required for the database schema to match the Model definitions attached to the DataSource. Note: This method applies only to SQL connectors.
Name | Type | Description |
---|---|---|
[models] |
String or Array.<String>
|
A model name or an array of model names. If not present, apply to all models. |
Name | Type | Description |
---|---|---|
result |
Boolean
|
Whether or not migrations are required. |
Check if the backend is a relational DB
Name | Type | Description |
---|---|---|
result |
Boolean
|
Return JSON object describing all operations.
Example return value:
{
find: {
remoteEnabled: true,
accepts: [...],
returns: [...]
enabled: true
},
save: {
remoteEnabled: true,
prototype: true,
accepts: [...],
returns: [...],
enabled: true
},
...
}
Ping the underlying connector to test the connections
Name | Type | Description |
---|---|---|
[cb] |
Function
|
Callback function |
Check if the data source is ready. Returns a Boolean value.
Name | Type | Description |
---|---|---|
obj |
Object
|
Deferred method call if the connector is not fully connected yet |
args |
Object
|
argument passing to method call. |
Check the data source supports the specified types.
Name | Type | Description |
---|---|---|
types |
String or Array.<String>
|
Type name or an array of type names. |
Name | Type | Description |
---|---|---|
result |
Boolean
|
true if all types are supported by the data source |
Return table name for specified modelName
.
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name. |
Name | Type | Description |
---|---|---|
result |
String
|
The table name. |
Run a transaction against the DataSource.
This method can be used in different ways based on the passed arguments and type of underlying data source:
If no execute()
function is provided and the underlying DataSource is a
database that supports transactions, a Promise is returned that resolves to
an EventEmitter representing the transaction once it is ready.
transaction.models
can be used to receive versions of the DataSource's
model classes which are bound to the created transaction, so that all their
database methods automatically use the transaction. At the end of all
database transactions, transaction.commit()
can be called to commit the
transactions, or transaction.rollback()
to roll them back.
If no execute()
function is provided on a transient or memory DataSource,
the EventEmitter representing the transaction is returned immediately. For
backward compatibility, this object also supports transaction.exec()
instead of transaction.commit()
, and calling transaction.rollback()
is
not required on such transient and memory DataSource instances.
If an execute()
function is provided, then it is called as soon as the
transaction is ready, receiving transaction.models
as its first
argument. transaction.commit()
and transaction.rollback()
are then
automatically called at the end of execute()
, based on whether exceptions
happen during execution or not. If no callback is provided to be called at
the end of the execution, a Promise object is returned that is resolved or
rejected as soon as the execution is completed, and the transaction is
committed or rolled back.
Name | Type | Description |
---|---|---|
execute |
Function
|
The execute function, called with (models). Note that the instances in |
options |
Object
|
The options to be passed to |
cb |
Function
|
Callback called with (err) |
Name | Type | Description |
---|---|---|
result |
Promise or EventEmitter
|
Model class: base class for all persistent objects.
ModelBaseClass
mixes Validatable
and Hookable
classes methods
Name | Type | Description |
---|---|---|
data |
Object
|
Initial object data |
options |
Object
|
An object to control the instantiation |
Name | Type | Description |
---|---|---|
result |
ModelBaseClass
|
an instance of the ModelBaseClass |
Define a property on the model.
Name | Type | Description |
---|---|---|
prop |
String
|
Property name |
params |
Object
|
Various property configuration |
getMergePolicy()
provides model merge policies to apply when extending
a child model from a base model. Such a policy drives the way parent/child model
properties/settings are merged/mixed-in together.
Below is presented the expected merge behaviour for each option. NOTE: This applies to top-level settings properties
Any
{replace: true}
(default): child replaces the value from parentnull
on child setting deletes the inherited settingArrays:
{replace: false}
: unique elements of parent and child cumulate{rank: true}
adds the model inheritance rank to array
elements of type Object {} as internal property __rank
Object {}:
{replace: false}
: deep merges parent and child objects{patch: true}
: child replaces inner properties from parentThe recommended built-in merge policy is as follows. It is returned by getMergePolicy()
when calling the method with option {configureModelMerge: true}
.
{
description: {replace: true}, // string or array
options: {patch: true}, // object
hidden: {replace: false}, // array
protected: {replace: false}, // array
indexes: {patch: true}, // object
methods: {patch: true}, // object
mixins: {patch: true}, // object
relations: {patch: true}, // object
scope: {replace: true}, // object
scopes: {patch: true}, // object
acls: {rank: true}, // array
// this setting controls which child model property's value allows deleting
// a base model's property
__delete: null,
// this setting controls the default merge behaviour for settings not defined
// in the mergePolicy specification
__default: {replace: true},
}
The legacy built-in merge policy is as follows, it is retuned by getMergePolicy()
when avoiding option configureModelMerge
.
NOTE: it also provides the ACLs ranking in addition to the legacy behaviour, as well
as fixes for settings 'description' and 'relations': matching relations from child
replace relations from parents.
{
description: {replace: true}, // string or array
properties: {patch: true}, // object
hidden: {replace: false}, // array
protected: {replace: false}, // array
relations: {acls: true}, // object
acls: {rank: true}, // array
}
getMergePolicy()
can be customized using model's setting configureModelMerge
as follows:
{
// ..
options: {
configureModelMerge: {
// merge options
}
}
// ..
}
NOTE: mergePolicy parameter can also defined at JSON model definition root
getMergePolicy()
method can also be extended programmatically as follows:
myModel.getMergePolicy = function(options) {
const origin = myModel.base.getMergePolicy(options);
return Object.assign({}, origin, {
// new/overriding options
});
};
Name | Type | Description |
---|---|---|
options |
Object
|
option
|
Name | Type | Description |
---|---|---|
result |
Object
|
mergePolicy The model merge policy to apply when using the current model as base class for a child model |
Get model property type.
Name | Type | Description |
---|---|---|
propName |
String
|
Property name |
Name | Type | Description |
---|---|---|
result |
String
|
Name of property type |
Gets properties defined with 'updateOnly' flag set to true from the model. This flag is also set to true internally for the id property, if this property is generated and IdInjection is true.
Name | Type | Description |
---|---|---|
result |
updateOnlyProps
|
List of properties with updateOnly set to true. |
Checks if property is hidden.
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name |
Name | Type | Description |
---|---|---|
result |
Boolean
|
true or false if hidden or not. |
Checks if property is protected.
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name |
Name | Type | Description |
---|---|---|
result |
Boolean
|
true or false if proptected or not. |
Name | Type | Description |
---|---|---|
anotherClass |
String
|
could be string or class. Name of the class or the class itself |
options |
Object
|
An object to control the instantiation |
Name | Type | Description |
---|---|---|
result |
ModelClass
|
Return string representation of class
This overrides the default toString()
method
Get model property type.
Name | Type | Description |
---|---|---|
propName |
String
|
Property name |
Name | Type | Description |
---|---|---|
result |
String
|
Name of property type |
Reset dirty attributes. This method does not perform any database operations; it just resets the object to its initial state.
Convert model instance to a plain JSON object. Returns a canonical object representation (no getters and setters).
Name | Type | Description |
---|---|---|
onlySchema |
Boolean
|
Restrict properties to dataSource only. Default is false. If true, the function returns only properties defined in the schema; Otherwise it returns all enumerable properties. |
removeHidden |
Boolean
|
Boolean flag as part of the transformation. If true, then hidden properties should not be brought out. |
removeProtected |
Boolean
|
Boolean flag as part of the transformation. If true, then protected properties should not be brought out. |
Name | Type | Description |
---|---|---|
result |
Object
|
returns Plain JSON object |
A String whose value is a valid representation of a Date. Use this type if you need to preserve the format of the value and still check if it's valid. Example:
var loopback = require('loopback');
var dt = new loopback.DateString('2001-01-01');
dt.toString();
// '2001-01-01'
dt._date.toISOString();
// '2001-01-01T00:00:00.000Z'
You can use this definition on your models as well:
{
"name": "Person",
"base": "PersistedModel",
"properties": {
"name": {
"type": "string"
},
"dob": {
"type": "DateString",
"required": true
},
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Name | Type | Description |
---|---|---|
value |
String
|
Returns the JSON representation of the DateString object.
Name | Type | Description |
---|---|---|
result |
String
|
A JSON string. |
Returns the value of DateString in its original form.
Name | Type | Description |
---|---|---|
result |
String
|
The Date as a String. |
The GeoPoint object represents a physical location.
For example:
var loopback = require(‘loopback’);
var here = new loopback.GeoPoint({lat: 10.32424, lng: 5.84978});
Embed a latitude / longitude point in a model.
var CoffeeShop = loopback.createModel('coffee-shop', {
location: 'GeoPoint'
});
You can query LoopBack models with a GeoPoint property and an attached data source using geo-spatial filters and sorting. For example, the following code finds the three nearest coffee shops.
CoffeeShop.attachTo(oracle);
var here = new GeoPoint({lat: 10.32424, lng: 5.84978});
CoffeeShop.find( {where: {location: {near: here}}, limit:3}, function(err, nearbyShops) {
console.info(nearbyShops); // [CoffeeShop, ...]
});
Name | Type | Description |
---|---|---|
Options |
Object
|
Object with two Number properties: lat and long. |
Options |
Array
|
Array with two Number entries: [lat,long]. |
Name | Type | Description |
---|---|---|
lat |
Number
|
The latitude point in degrees. Range: -90 to 90. |
lng |
Number
|
The longitude point in degrees. Range: -180 to 180. |
Name | Type | Description |
---|---|---|
lat |
Number
|
The latitude point in degrees. Range: -90 to 90. |
lng |
Number
|
The longitude point in degrees. Range: -180 to 180. |
Name | Type | Description |
---|---|---|
lat |
Number
|
The latitude in degrees. |
lng |
Number
|
The longitude in degrees. |
Determine the spherical distance between two GeoPoints.
Name | Type | Description |
---|---|---|
pointA |
GeoPoint
|
Point A |
pointB |
GeoPoint
|
Point B |
options |
Object
|
Options object with one key, 'type'. See below. |
Name | Type | Description |
---|---|---|
type |
String
|
Unit of measurement, one of:
|
Determine the spherical distance to the given point. Example:
var loopback = require(‘loopback’);
var here = new loopback.GeoPoint({lat: 10, lng: 10});
var there = new loopback.GeoPoint({lat: 5, lng: 5});
loopback.GeoPoint.distanceBetween(here, there, {type: 'miles'}) // 438
Name | Type | Description |
---|---|---|
point |
Object
|
GeoPoint object to which to measure distance. |
options |
Object
|
Options object with one key, 'type'. See below. |
Name | Type | Description |
---|---|---|
type |
String
|
Unit of measurement, one of:
|
Simple serialization.
Hooks object.
Name | Type | Description |
---|---|---|
actionName |
string
|
The name of the action that triggers the hook. |
work |
Function
|
The 2nd phase of the trigger. |
data |
|
The value(s) to provide to the 1st phase ( |
|
Name | Type | Description |
---|---|---|
callback |
Function
|
Utility Function to allow interleave before and after high computation tasks
Name | Type | Description |
---|---|---|
tasks |
|
|
callback |
|
Inclusion - Model mixin.
Find related items with an array of foreign keys by page
Name | Type | Description |
---|---|---|
model |
|
The model class |
filter |
|
The query filter |
fkName |
|
The name of the foreign key property |
pageSize |
|
The size of page |
options |
|
Options |
cb |
|
Make the DB Call, fetch all target objects
Enables you to load relations of several objects and optimize numbers of requests.
Examples:
Load all users' posts with only one additional request:
User.include(users, 'posts', function() {});
Or
User.include(users, ['posts'], function() {});
Load all users posts and passports with two additional requests:
User.include(users, ['posts', 'passports'], function() {});
Load all passports owner (users), and all posts of each owner loaded:
Passport.include(passports, {owner: 'posts'}, function() {});
Passport.include(passports, {owner: ['posts', 'passports']});
``` Passport.include(passports, {owner: [{posts: 'images'}, 'passports']});
Name | Type | Description |
---|---|---|
objects |
Array
|
Array of instances |
include |
String or Object or Array
|
Which relations to load. |
[options] |
Object
|
Options for CRUD |
cb |
Function
|
Callback called when relations are loaded |
Handle Inclusion of EmbedsMany/EmbedsManyWithBelongsTo/EmbedsOne Relations. Since Embedded docs are part of parents, no need to make db calls. Let the related function be called for each object to fetch the results from cache.
TODO: Optimize EmbedsManyWithBelongsTo relation DB Calls
Name | Type | Description |
---|---|---|
callback |
|
Handle inclusion of HasMany relation
Name | Type | Description |
---|---|---|
callback |
|
Handle inclusion of HasMany relation
Name | Type | Description |
---|---|---|
callback |
|
Handle inclusion of HasManyThrough/HasAndBelongsToMany/Polymorphic HasManyThrough relations
Name | Type | Description |
---|---|---|
callback |
|
Handle Inclusion of BelongsTo/HasOne relation
Name | Type | Description |
---|---|---|
callback |
|
Handle Inclusion of Polymorphic BelongsTo relation
Name | Type | Description |
---|---|---|
callback |
|
Handle Inclusion of Polymorphic HasOne relation
Name | Type | Description |
---|---|---|
callback |
|
Handle inclusion of ReferencesMany relation
Name | Type | Description |
---|---|---|
callback |
|
Process Polymorphic objects of each type (modelType)
Name | Type | Description |
---|---|---|
modelType |
String
|
|
callback |
|
Process Each Model Object and make sure specified relations are included
Name | Type | Description |
---|---|---|
obj |
Model
|
Single Mode object for which inclusion is needed |
callback |
|
Name | Type | Description |
---|---|---|
result |
|
Sets the related objects as a property of Parent Object
Name | Type | Description |
---|---|---|
result |
Array.<Model> or Model
|
Related Object/Objects |
cb |
|
Handle the fetched target objects
Name | Type | Description |
---|---|---|
err |
|
|
{Array<Model>}targets |
|
Name | Type | Description |
---|---|---|
result |
|
Process fetched related objects
Name | Type | Description |
---|---|---|
err |
|
|
targets |
Array.<Model>
|
Name | Type | Description |
---|---|---|
result |
|
Process fetched related objects
Name | Type | Description |
---|---|---|
err |
|
|
targets |
Array.<Model>
|
Name | Type | Description |
---|---|---|
result |
|
Process fetched related objects
Name | Type | Description |
---|---|---|
err |
|
|
targets |
Array.<Model>
|
Name | Type | Description |
---|---|---|
result |
|
Process fetched related objects
Name | Type | Description |
---|---|---|
err |
|
|
targets |
Array.<Model>
|
Name | Type | Description |
---|---|---|
result |
|
Handle the results of Through model objects and fetch the modelTo items
Name | Type | Description |
---|---|---|
err |
|
|
throughObjs |
Array.<Model>
|
Name | Type | Description |
---|---|---|
result |
|
ModelBuilder - A builder to define data models.
Name | Type | Description |
---|---|---|
definitions |
Object
|
Definitions of the models. |
models |
Object
|
Model constructors |
Extend the model with the specified model, properties, and other settings. For example, to extend an existing model, for example, a built-in model:
var Customer = User.extend('customer', {
accountId: String,
vip: Boolean
});
To extend the base model, essentially creating a new model:
var user = loopback.Model.extend('user', properties, options);
Name | Type | Description |
---|---|---|
className |
String
|
Name of the new model being defined. |
subClassProperties |
Object
|
child model properties, added to base model properties. |
subClassSettings |
Object
|
child model settings such as relations and acls, merged with base model settings. |
Merge parent and child model settings according to the provided merge policy.
Below is presented the expected merge behaviour for each option of the policy. NOTE: This applies to top-level settings properties
Any
{replace: true}
(default): child replaces the value from parentnull
on child setting deletes the inherited settingArrays:
{replace: false}
: unique elements of parent and child cumulate{rank: true}
adds the model inheritance rank to array
elements of type Object {} as internal property __rank
Object {}:
{replace: false}
: deep merges parent and child objects{patch: true}
: child replaces inner properties from parentHere is an example of merge policy:
{
description: {replace: true}, // string or array
properties: {patch: true}, // object
hidden: {replace: false}, // array
protected: {replace: false}, // array
relations: {acls: true}, // object
acls: {rank: true}, // array
}
Name | Type | Description |
---|---|---|
baseClassSettings |
Object
|
parent model settings. |
subClassSettings |
Object
|
child model settings. |
mergePolicy |
Object
|
merge policy, as defined in |
Register a property for the model class
Name | Type | Description |
---|---|---|
propertyName |
String
|
Name of the property. |
Introspect the JSON document to build a corresponding model.
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
json |
Object
|
The JSON object |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
ModelClass
|
The generated model class constructor. |
Build models from schema definitions
schemas
can be one of the following:
Name | Type | Description |
---|---|---|
schemas |
|
The schemas |
Name | Type | Description |
---|---|---|
result |
Object.<string, ModelClass>
|
A map of model constructors keyed by model name. |
Define a model class. Simple example:
var User = modelBuilder.define('User', {
email: String,
password: String,
birthDate: Date,
activated: Boolean
});
More advanced example:
var User = modelBuilder.define('User', {
email: { type: String, limit: 150, index: true },
password: { type: String, limit: 50 },
birthDate: Date,
registrationDate: {type: Date, default: function () { return new Date }},
activated: { type: Boolean, default: false }
});
Name | Type | Description |
---|---|---|
className |
String
|
Name of class |
properties |
Object
|
Hash of class properties in format |
settings |
Object
|
Other configuration of class |
parent |
Function
|
Parent model |
Define single property named propertyName
on model
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
propertyName |
String
|
Name of property |
propertyDefinition |
Object
|
Property settings |
Define a new value type that can be used in model schemas as a property type.
Name | Type | Description |
---|---|---|
type |
function()
|
Type constructor. |
aliases |
Array.<string>
|
Optional list of alternative names for this type. |
Extend existing model with specified properties
Example: Instead of extending a model with attributes like this (for example):
db.defineProperty('Content', 'competitionType',
{ type: String });
db.defineProperty('Content', 'expiryDate',
{ type: Date, index: true });
db.defineProperty('Content', 'isExpired',
{ type: Boolean, index: true });
This method enables you to extend a model as follows (for example):
db.extendModel('Content', {
competitionType: String,
expiryDate: { type: Date, index: true },
isExpired: { type: Boolean, index: true }
});
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
properties |
Object
|
JSON object specifying properties. Each property is a key whos value is either the type or |
Name | Type | Description |
---|---|---|
type |
String
|
Datatype of property: Must be an LDL type. |
index |
Boolean
|
True if the property is an index; false otherwise. |
Get a model by name.
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
forceCreate |
Boolean
|
Whether the create a stub for the given name if a model doesn't exist. |
Name | Type | Description |
---|---|---|
result |
ModelClass
|
The model class |
Get the model definition by name
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
ModelDefinition
|
The model definition |
Get the schema name. If no parameter is given, then an anonymous model name is generated and returned.
Name | Type | Description |
---|---|---|
name |
string
|
The optional name parameter. |
Name | Type | Description |
---|---|---|
result |
string
|
The schema name. |
Resolve the type string to be a function, for example, 'String' to String. Returns {Function} if the type is resolved
Name | Type | Description |
---|---|---|
type |
String
|
The type string, such as 'number', 'Number', 'boolean', or 'String'. This parameter is case insensitive. |
RelationMixin class. Use to define relationships between models.
Declare "belongsTo" relation that sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.
For example, if an application includes users and posts, and each post can be written by exactly one user.
The following code specifies that Post
has a reference called author
to the User
model via the userId
property of Post
as the foreign key.
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
You can then access the author in one of the following styles. Get the User object for the post author asynchronously:
post.author(callback);
Get the User object for the post author synchronously:
post.author();
Set the author to be the given user:
post.author(user)
Examples:
Suppose the model Post has a belongsTo relationship with User (the author of the post). You could declare it this way:
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
When a post is loaded, you can load the related author with:
post.author(function(err, user) {
// the user variable is your user object
});
The related object is cached, so if later you try to get again the author, no additional request will be made. But there is an optional boolean parameter in first position that set whether or not you want to reload the cache:
post.author(true, function(err, user) {
// The user is reloaded, even if it was already cached.
});
This optional parameter default value is false, so the related object will be loaded from cache if available.
Name | Type | Description |
---|---|---|
modelTo |
Class or String
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
primaryKey |
String
|
Property name of primary key field. |
foreignKey |
String
|
Name of foreign key property. |
scope |
Object or Function
|
Explicitly define additional scopes. |
properties |
Object
|
Properties inherited from the parent object. |
options |
Object
|
Property level options. |
options.invertProperties |
Boolean
|
Specify if the properties should be inverted. |
Represent a model that can embed many instances of another model.
For example, a Customer can have multiple email addresses and each email address is a complex object that contains label and address.
Define the relation code in bootscript:
Customer.embedsMany(EmailAddress, {
as: 'emails', // default to the relation name - emailAddresses
property: 'emailList' // default to emailAddressItems
});
OR, define the relation in the model definition:
Definition of Customer model:
{
"name": "Customer",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number"
}
},
"validations": [],
"relations": {
"emails": {
"type": "embedsMany",
"model": "EmailAddress",
"property": "emailList",
"options": {
"validate": true,
"forceId": false
}
}
},
"acls": [],
"methods": {}
}
Definition of EmailAddress model:
{
"name": "EmailAddress",
"base": "Model",
"idInjection": true,
"properties": {
"label": {
"type": "string"
},
"address": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Sample embedded model data:
{
id: 1,
name: 'John Smith',
emails: [{
label: 'work',
address: 'john@xyz.com'
}, {
label: 'home',
address: 'john@gmail.com'
}]
}
Supported helper methods:
Name | Type | Description |
---|---|---|
modelTo |
Object or String
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
property |
String
|
Name of the property for the embedded item. |
default |
Any
|
The default value. |
options |
Object
|
Options to specify for the relationship. |
options.forceId |
Boolean
|
Force generation of id for embedded items. Default is false. |
options.validate |
Boolean
|
Denote if the embedded items should be validated. Default is true. |
options.persistent |
Boolean
|
Denote if the embedded items should be persisted. Default is false. |
polymorphic |
String
|
Define a polymorphic relation name. |
scope |
Object or Function
|
Explicitly define additional scopes. |
properties |
Object
|
Properties inherited from the parent object. |
methods |
Function
|
Scoped methods for the given relation. |
Represent a model that embeds another model.
For example, a Customer embeds one billingAddress from the Address model.
Customer.embedsOne(Address, {
as: 'address', // default to the relation name - address
property: 'billingAddress' // default to addressItem
});
OR, define the relation in the model definition:
Definition of Customer model:
{
"name": "Customer",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number"
}
},
"validations": [],
"relations": {
"address": {
"type": "embedsOne",
"model": "Address",
"property": "billingAddress",
"options": {
"validate": true,
"forceId": false
}
}
},
"acls": [],
"methods": {}
}
Definition of Address model:
{
"name": "Address",
"base": "Model",
"idInjection": true,
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
},
"zipCode": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Sample embedded model data:
{
id: 1,
name: 'John Smith',
billingAddress: {
street: '123 Main St',
city: 'San Jose',
state: 'CA',
zipCode: '95124'
}
}
Supported helper methods:
Name | Type | Description |
---|---|---|
modelTo |
Object or String
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
property |
String
|
Name of the property for the embedded item. |
default |
Any
|
The default value. |
options |
Object
|
Options to specify for the relationship. |
options.forceId |
Boolean
|
Force generation of id for embedded items. Default is false. |
options.validate |
Boolean
|
Denote if the embedded items should be validated. Default is true. |
options.persistent |
Boolean
|
Denote if the embedded items should be persisted. Default is false. |
scope |
Object or Function
|
Explicitly define additional scopes. |
properties |
Object
|
Properties inherited from the parent object. |
methods |
Function
|
Scoped methods for the given relation. |
A hasAndBelongsToMany relation creates a direct many-to-many connection with another model, with no intervening model.
For example, if your application includes users and groups, with each group having many users and each user appearing in many groups, you could declare the models this way:
User.hasAndBelongsToMany('groups', {model: Group, foreignKey: 'groupId'});
Then, to get the groups to which the user belongs:
user.groups(callback);
Create a new group and connect it with the user:
user.groups.create(data, callback);
Connect an existing group with the user:
user.groups.add(group, callback);
Remove the user from the group:
user.groups.remove(group, callback);
Name | Type | Description |
---|---|---|
modelTo |
String or Object
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
foreignKey |
String
|
Property name of foreign key field. |
throughTable |
String
|
The table name of the through model. |
through |
String
|
Name of the through model. |
polymorphic |
String
|
Define a polymorphic relation name. |
scope |
Object or Function
|
Explicitly define additional scopes. |
model |
Object
|
The model object. |
Define a "one to many" relationship by specifying the model name.
Examples:
User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
Book.hasMany(Chapter);
Or, equivalently:
Book.hasMany('chapters', {model: Chapter});
Query and create related models:
Book.create(function(err, book) {
// Create a chapter instance ready to be saved in the data source.
var chapter = book.chapters.build({name: 'Chapter 1'});
// Save the new chapter
chapter.save();
// you can also call the Chapter.create method with the `chapters` property which will build a chapter
// instance and save the it in the data source.
book.chapters.create({name: 'Chapter 2'}, function(err, savedChapter) {
// this callback is optional
});
// Query chapters for the book
book.chapters(function(err, chapters) {
// all chapters with bookId = book.id
console.log(chapters);
});
// Query chapters for the book with a filter
book.chapters({where: {name: 'test'}, function(err, chapters) {
// All chapters with bookId = book.id and name = 'test'
console.log(chapters);
});
});
Name | Type | Description |
---|---|---|
modelTo |
Object or String
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
foreignKey |
String
|
Property name of foreign key field. |
polymorphic |
String
|
Define a polymorphic relation name. |
through |
String
|
Name of the through model. |
keyThrough |
String
|
Property name of the foreign key in the through model. |
scope |
Object or Function
|
Explicitly define additional scopes. |
invert |
Boolean
|
Specify if the relation is inverted. |
model |
Object
|
The model object. |
Define a "one to one" relationship by specifying the model name.
Examples:
Supplier.hasOne(Account, {as: 'account', foreignKey: 'supplierId'});
If the target model doesn’t have a foreign key property, LoopBack will add a property with the same name.
The type of the property will be the same as the type of the target model’s id property.
Please note the foreign key property is defined on the target model (in this example, Account).
If you don’t specify them, then LoopBack derives the relation name and foreign key as follows:
Build a new account for the supplier with the supplierId to be set to the id of the supplier.
var supplier = supplier.account.build(data);
Create a new account for the supplier. If there is already an account, an error will be reported.
supplier.account.create(data, function(err, account) {
...
});
Find the supplier's account model.
supplier.account(function(err, account) {
...
});
Update the associated account.
supplier.account.update({balance: 100}, function(err, account) {
...
});
Remove the account for the supplier.
supplier.account.destroy(function(err) {
...
});
Name | Type | Description |
---|---|---|
modelTo |
Object or String
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
primaryKey |
String
|
Property name of primary key field. |
foreignKey |
String
|
Property name of foreign key field. |
polymorphic |
String
|
Define a polymorphic relation name. |
scope |
Object or Function
|
Explicitly define additional scopes. |
model |
Object
|
The model object. |
properties |
Object
|
Properties inherited from the parent object. |
methods |
Function
|
Scoped methods for the given relation. |
References one or more instances of the target model.
For example, a Customer model references one or more instances of the Account model.
Define the relation in the model definition:
Definition of Customer model:
{
"name": "Customer",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number"
}
},
"validations": [],
"relations": {
"accounts": {
"type": "referencesMany",
"model": "Account",
"foreignKey": "accountIds",
"options": {
"validate": true,
"forceId": false
}
}
},
"acls": [],
"methods": {}
}
Definition of Account model:
{
"name": "Account",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string"
},
"balance": {
"type": "number"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
On the bootscript, create a customer instance and for that customer instance reference many account instances.
For example:
var Customer = app.models.Customer;
var accounts = [
{
name: 'Checking',
balance: 5000
},
{
name: 'Saving',
balance: 2000
}
];
Customer.create({name: 'Mary Smith'}, function(err, customer) {
console.log('Customer:', customer);
async.each(accounts, function(account, done) {
customer.accounts.create(account, done);
}, function(err) {
console.log('Customer with accounts:', customer);
customer.accounts(console.log);
cb(err);
});
});
Sample referencesMany model data:
{
id: 1,
name: 'John Smith',
accounts: [
"saving-01", "checking-01",
]
}
Supported helper methods:
Name | Type | Description |
---|---|---|
modelTo |
Object or String
|
Model object (or String name of model) to which you are creating the relationship. |
params |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
as |
String
|
Name of the property in the referring model that corresponds to the foreign key field in the related model. |
default |
Any
|
The default value. |
options |
Object
|
Options to specify for the relationship. |
options.forceId |
Boolean
|
Force generation of id for embedded items. Default is false. |
options.validate |
Boolean
|
Denote if the embedded items should be validated. Default is true. |
options.persistent |
Boolean
|
Denote if the embedded items should be persisted. Default is false. |
scope |
Object or Function
|
Explicitly define additional scopes. |
foreignKey |
String
|
Property name of foreign key field. |
properties |
Object
|
Properties inherited from the parent object. |
methods |
Function
|
Scoped methods for the given relation. |
ObserverMixin class. Use to add observe/notifyObserversOf APIs to other classes.
Unregister all asynchronous observers for the given operation (event).
Example:
Remove all observers connected to the before save
operation.
MyModel.clearObservers('before save');
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name. |
Run the given function with before/after observers.
It's done in three serial asynchronous steps:
If an error happens, it fails first and calls the callback with err.
Example:
var context = {
Model: Model,
instance: obj,
isNewInstance: true,
hookState: hookState,
options: options,
};
function work(done) {
process.nextTick(function() {
done(null, 1);
});
}
Model.notifyObserversAround('execute', context, work, function(err) {
if (err) return cb(err);
// user can specify the logic after the observers have been notified
});
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
context |
Context
|
The context object |
fn |
Function
|
The task to be invoked as fn(done) or fn(context, done) |
callback |
Function
|
The callback function |
Name | Type | Description |
---|---|---|
result |
|
Invoke all async observers for the given operation(s).
Example:
Notify all async observers for the before save
operation.
var context = {
Model: Model,
instance: obj,
isNewInstance: true,
hookState: hookState,
options: options,
};
Model.notifyObserversOf('before save', context, function(err) {
if (err) return cb(err);
// user can specify the logic after the observers have been notified
});
Name | Type | Description |
---|---|---|
operation |
String or Array.<String>
|
The operation name(s). |
context |
Object
|
Operation-specific context. |
callback |
function(Error=)
|
The callback to call when all observers have finished. |
Register an asynchronous observer for the given operation (event).
Example:
Registers a before save
observer for a given model.
MyModel.observe('before save', function filterProperties(ctx, next) {
if (ctx.options && ctx.options.skipPropertyFilter) return next();
if (ctx.instance) {
FILTERED_PROPERTIES.forEach(function(p) {
ctx.instance.unsetAttribute(p);
});
} else {
FILTERED_PROPERTIES.forEach(function(p) {
delete ctx.data[p];
});
}
next();
});
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name. |
listener |
function
|
The listener function. It will be invoked with |
Unregister an asynchronous observer for the given operation (event).
Example:
MyModel.removeObserver('before save', function removedObserver(ctx, next) {
// some logic user want to apply to the removed observer...
next();
});
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name. |
listener |
function
|
The listener function. |
TransactionMixin class. Use to add transaction APIs to a model class.
Begin a new transaction.
A transaction can be committed or rolled back. If timeout happens, the transaction will be rolled back. Please note a transaction is typically associated with a pooled connection. Committing or rolling back a transaction will release the connection back to the pool.
Once the transaction is committed or rolled back, the connection property will be set to null to mark the transaction to be inactive. Trying to commit or rollback an inactive transaction will receive an error from the callback.
Please also note that the transaction is only honored with the same data source/connector instance. CRUD methods will not join the current transaction if its model is not attached the same data source.
Example:
To pass the transaction context to one of the CRUD methods, use the options
argument with transaction
property, for example,
MyModel.beginTransaction('READ COMMITTED', function(err, tx) {
MyModel.create({x: 1, y: 'a'}, {transaction: tx}, function(err, inst) {
MyModel.find({x: 1}, {transaction: tx}, function(err, results) {
// ...
tx.commit(function(err) {...});
});
});
});
Name | Type | Description |
---|---|---|
options |
Object or String
|
Options to be passed upon transaction. Can be one of the forms:
Valid values of
|
cb |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
result |
Promise
|
Returns a callback promise. |
Commit a transaction and release it back to the pool.
Example:
MyModel.beginTransaction('READ COMMITTED', function(err, tx) {
// some crud operation of your choice
tx.commit(function(err) {
// release the connection pool upon committing
tx.close(err);
});
});
Name | Type | Description |
---|---|---|
cb |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
result |
Promise
|
Returns a callback promise. |
Rollback a transaction and release it back to the pool.
Example:
MyModel.beginTransaction('READ COMMITTED', function(err, tx) {
// some crud operation of your choice
tx.rollback(function(err) {
// release the connection pool upon committing
tx.close(err);
});
});
Name | Type | Description |
---|---|---|
cb |
Function
|
Callback function. |
Name | Type | Description |
---|---|---|
result |
Promise
|
Returns a callback promise. |
This class provides methods that add validation cababilities to models.
Each of the validations runs when the obj.isValid()
method is called.
All of the methods have an options object parameter that has a
message
property. When there is only a single error message, this property is just a string;
for example: Post.validatesPresenceOf('title', { message: 'can not be blank' });
In more complicated cases it can be a set of messages, for each possible error condition; for example:
User.validatesLengthOf('password', { min: 6, max: 20, message: {min: 'too short', max: 'too long'}});
Validate using custom validation function.
Example:
User.validate('name', customValidator, {message: 'Bad name'});
function customValidator(err) {
if (this.name === 'bad') err();
});
var user = new User({name: 'Peter'});
user.isValid(); // true
user.name = 'bad';
user.isValid(); // false
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
validatorFn |
Function
|
Custom validation function. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
message |
String
|
Optional error message if property is not valid. Default error message: " is invalid". |
allowNull |
Boolean
|
Whether null values are allowed. |
Validate using custom asynchronous validation function.
Example:
User.validateAsync('name', customValidator, {message: 'Bad name'});
function customValidator(err, done) {
process.nextTick(function () {
if (this.name === 'bad') err();
done();
});
});
var user = new User({name: 'Peter'});
user.isValid(); // false (because async validation setup)
user.isValid(function (isValid) {
isValid; // true
})
user.name = 'bad';
user.isValid(); // false
user.isValid(function (isValid) {
isValid; // false
})
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
validatorFn |
Function
|
Custom validation function. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
message |
String
|
Optional error message if property is not valid. Default error message: " is invalid". |
allowNull |
Boolean
|
Whether null values are allowed. |
Validate absence of one or more specified properties.
A model should not include a property to be considered valid; fails when validated field is not blank.
For example, validate absence of reserved
Post.validatesAbsenceOf('reserved', { unless: 'special' });
Name | Type | Description |
---|---|---|
propertyName |
String
|
One or more property names. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
message |
String
|
Error message to use instead of default. |
if |
String
|
Validate only if |
unless |
String
|
Validate only if |
Validate if a value for a property is a Date.
Example
User.validatesDateOf('today', {message: 'today is not a date!'});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
message |
String
|
Error message to use instead of default. |
Validate exclusion in a set.
Require a property value not be in the specified array.
Example: Company.validatesExclusionOf('domain', {in: ['www', 'admin']});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
in |
Array
|
Property must not match any of the values in the array to be valid. |
message |
String
|
Optional error message if property is not valid. Default error message: "is reserved". |
allowNull |
Boolean
|
Whether null values are allowed. |
Validate format.
Require a model to include a property that matches the given format.
Example: User.validatesFormatOf('name', {with: /\w+/});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
with |
RegExp
|
Regular expression to validate format. |
message |
String
|
Optional error message if property is not valid. Default error message: " is invalid". |
allowNull |
Boolean
|
Whether null values are allowed. |
Validate inclusion in set.
Require a value for property to be in the specified array.
Example:
User.validatesInclusionOf('gender', {in: ['male', 'female']});
User.validatesInclusionOf('role', {
in: ['admin', 'moderator', 'user'], message: 'is not allowed'
});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
in |
Array
|
Property must match one of the values in the array to be valid. |
message |
String
|
Optional error message if property is not valid. Default error message: "is not included in the list". |
allowNull |
Boolean
|
Whether null values are allowed. |
Validate length.
Require a property length to be within a specified range.
There are three kinds of validations: min, max, is.
Default error messages:
Example: length validations
User.validatesLengthOf('password', {min: 7});
User.validatesLengthOf('email', {max: 100});
User.validatesLengthOf('state', {is: 2});
User.validatesLengthOf('nick', {min: 3, max: 15});
Example: length validations with custom error messages
User.validatesLengthOf('password', {min: 7, message: {min: 'too weak'}});
User.validatesLengthOf('state', {is: 2, message: {is: 'is not valid state name'}});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
is |
Number
|
Value that property must equal to validate. |
min |
Number
|
Value that property must be less than to be valid. |
max |
Number
|
Value that property must be less than to be valid. |
message |
Object
|
Optional object with string properties for custom error message for each validation: is, min, or max. |
Validate numericality.
Requires a value for property to be either an integer or number.
Example
User.validatesNumericalityOf('age', { message: { number: 'is not a number' }});
User.validatesNumericalityOf('age', {int: true, message: { int: 'is not an integer' }});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
int |
Boolean
|
If true, then property must be an integer to be valid. |
allowBlank |
Boolean
|
Allow property to be blank. |
allowNull |
Boolean
|
Allow property to be null. |
message |
Object
|
Optional object with string properties for 'int' for integer validation. Default error messages: - number: is not a number
|
Validate presence of one or more specified properties.
Requires a model to include a property to be considered valid; fails when validated field is blank.
For example, validate presence of title
Post.validatesPresenceOf('title');
Validate that model has first, last, and age properties:
User.validatesPresenceOf('first', 'last', 'age');
Example with custom message
Post.validatesPresenceOf('title', {message: 'Cannot be blank'});
Name | Type | Description |
---|---|---|
propertyName |
String
|
One or more property names. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
message |
String
|
Error message to use instead of default. |
if |
String
|
Validate only if |
unless |
String
|
Validate only if |
Validate uniqueness of the value for a property in the collection of models.
Not available for all connectors. Currently supported with these connectors:
// The login must be unique across all User instances.
User.validatesUniquenessOf('login');
// Assuming SiteUser.belongsTo(Site)
// The login must be unique within each Site.
SiteUser.validateUniquenessOf('login', { scopedTo: ['siteId'] });
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
options |
Object
|
Configuration parameters; see below. |
Name | Type | Description |
---|---|---|
with |
RegExp
|
Regular expression to validate format. |
scopedTo |
Array.<String>
|
List of properties defining the scope. |
message |
String
|
Optional error message if property is not valid. Default error message: "is not unique". |
allowNull |
Boolean
|
Whether null values are allowed. |
ignoreCase |
String
|
Make the validation case insensitive. |
if |
String
|
Validate only if |
unless |
String
|
Validate only if |
This method performs validation and triggers validation hooks.
Before validation the obj.errors
collection is cleaned.
Each validation can add errors to obj.errors
collection.
If collection is not blank, validation failed.
NOTE: This method can be called as synchronous only when no asynchronous validation is configured. It's strongly recommended to run all validations as asyncronous.
Example: ExpressJS controller - render user if valid, show flash otherwise
user.isValid(function (valid) {
if (valid) res.render({user: user});
else res.flash('error', 'User is not valid'), console.log(user.errors), res.redirect('/users');
});
Another example:
user.isValid(function (valid) {
if (!valid) {
console.log(user.errors);
// => hash of errors
// => {
// => username: [errmessage, errmessage, ...],
// => email: ...
// => }
}
});
Name | Type | Description |
---|---|---|
callback |
Function
|
Called with (valid). |
Name | Type | Description |
---|---|---|
data |
Object
|
Data to be validated. |
options |
Object
|
Options to be specified upon validation. |
Name | Type | Description |
---|---|---|
result |
Boolean
|
True if no asynchronous validation is configured and all properties pass validation. |