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. |
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
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.
Name | Type | Description |
---|---|---|
modelClass |
Function
|
The model constructor |
Drop each model table and re-create. This method applies only to database connectors. For MongoDB, it drops and creates indexes.
WARNING: Calling this function deletes all data! Use autoupdate()
to preserve data.
Name | Type | Description |
---|---|---|
model |
String
|
Model to migrate. If not present, apply to all models. Can also be an array of Strings. |
[callback] |
Function
|
Callback function. Optional. |
Update existing database tables. This method applies only to database connectors.
Name | Type | Description |
---|---|---|
model |
String
|
Model to migrate. If not present, apply to all models. Can also be an array of Strings. |
[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 |
|
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 |
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. |
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 |
Define an operation to the data source
Name | Type | Description |
---|---|---|
name |
String
|
The operation name |
options |
Object
|
The options |
fn |
Function
|
The function |
Define single property named prop
on model
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
prop |
String
|
Name of property |
params |
Object
|
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 database connection
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. |
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. |
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 |
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 |
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 |
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 |
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
|
The options |
Callback |
Function
|
function. Optional. |
options |
Object
|
Discovery options. See below. |
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 |
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 |
|
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 |
Name | Type | Description |
---|---|---|
modelName |
String
|
The table/view name |
options |
Object
|
The options |
cb |
Function
|
Callback function. Optional |
Name | Type | Description |
---|---|---|
owner|schema |
String
|
The database owner or schema |
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) |
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 |
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 orschema |
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 |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
The options |
[cb] |
Function
|
The callback function |
Discover schema from a given modelName/view.
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. |
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. |
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
See ModelBuilder.getModel
See ModelBuilder.getModelDefinition
Get an operation's metadata.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Get the data source types
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
The data source type, such as ['db', 'nosql', 'mongodb'], ['rest'], or ['db', 'rdbms', 'mysql'] |
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 migrations needed 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. |
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 the data source supports the specified types.
Name | Type | Description |
---|---|---|
types |
String
|
Type name or an array of type names. Can also be array of Strings. |
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 |
Model class: base class for all persistent objects.
ModelBaseClass
mixes Validatable
and Hookable
classes methods
Name | Type | Description |
---|---|---|
data |
Object
|
Initial object data |
Define a property on the model.
Name | Type | Description |
---|---|---|
prop |
String
|
Property name |
params |
Object
|
Various property configuration |
Return string representation of class
This overrides the default toString()
method
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. |
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.
Find the idKey of a Model.
Name | Type | Description |
---|---|---|
m |
ModelConstructor
|
Model Constructor |
Name | Type | Description |
---|---|---|
result |
String
|
Utility Function to allow interleave before and after high computation tasks
Name | Type | Description |
---|---|---|
tasks |
|
|
callback |
|
Inclusion - Model mixin.
call relation specific include functions
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 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. |
properties |
Object
|
Properties to define for the model, added to properties of model being extended. |
settings |
Object
|
Model settings, such as relations and acls. |
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 |
|
{} |
Build models from schema definitions
schemas
can be one of the following:
Name | Type | Description |
---|---|---|
schemas |
|
The schemas |
Name | Type | Description |
---|---|---|
result |
Object
|
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 |
|
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
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'. It's 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:
```js
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. |
foreignKey |
String
|
Name of foreign key property. |
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. the relation |
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. |
model |
Object
|
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);
});
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. |
parameters |
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. |
model |
Object
|
Model object |
ObserverMixin class. Use to add observe/notifyObserversOf APIs to other classes.
Unregister all asynchronous observers for the given operation (event).
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name. |
Run the given function with before/after observers. It's done in three serial steps asynchronously:
If an error happens, it fails fast and calls the callback with err.
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).
Name | Type | Description |
---|---|---|
operation |
String or Array.<String>
|
The operation name(s). |
context |
Object
|
Operation-specific context. |
callback |
function(Error|undefined)
|
The callback to call when all observers has finished. |
Register an asynchronous observer for the given operation (event).
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name. |
listener |
function
|
The listener function. It will be invoked with |
Name | Type | Description |
---|---|---|
context |
Object
|
Operation-specific context. |
next |
function(Error|undefined)
|
The callback to call when the observer has finished. |
Unregister an asynchronous observer for the given operation (event).
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
Name | Type | Description |
---|---|---|
[options] |
Object or String
|
Options can be one of the forms: - Object: {isolationLevel: '...', timeout: 1000}
Valid values of
|
cb |
Function
|
Callback function. It calls back with (err, transaction). To pass the transaction context to one of the CRUD methods, use the
The 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. |
Commit a transaction and release it back to the pool
Name | Type | Description |
---|---|---|
cb |
Function
|
Callback function |
Name | Type | Description |
---|---|---|
result |
Promise
|
Rollback a transaction and release it back to the pool
Name | Type | Description |
---|---|---|
cb |
Function
|
Callback function |
Name | Type | Description |
---|---|---|
result |
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
|
See below. |
Name | Type | Description |
---|---|---|
message |
String
|
Optional error message if property is not valid. Default error message: " is invalid". |
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
|
See below |
Name | Type | Description |
---|---|---|
message |
String
|
Optional error message if property is not valid. Default error message: " is invalid". |
Validate absence of one or more specified properties. A model should not include a property to be considered valid; fails when validated field not blank.
For example, validate absence of reserved ``` Post.validatesAbsenceOf('reserved', { unless: 'special' });
Name | Type | Description |
---|---|---|
propertyName |
String
|
One or more property names. |
errMsg |
Object
|
Optional custom error message. Default is "can't be set" |
Name | Type | Description |
---|---|---|
message |
String
|
Error message to use instead of default. |
Validate exclusion. 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
|
Name | Type | Description |
---|---|---|
inArray |
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 reserved". |
Validate format. Require a model to include a property that matches the given format.
Require a model to include a property that matches the given format. Example:
User.validatesFormat('name', {with: /\w+/});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
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". |
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
|
Name | Type | Description |
---|---|---|
inArray |
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". |
Validate length. Require a property length to be within a specified range. 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
|
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: '...' }});
User.validatesNumericalityOf('age', {int: true, message: { int: '...' }});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
See below. |
Name | Type | Description |
---|---|---|
int |
Boolean
|
If true, then property must be an integer to be valid. |
message |
Object
|
Optional object with string properties for 'int' for integer validation. Default error messages:
|
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. |
errMsg |
Object
|
Optional custom error message. Default is "can't be blank" |
Name | Type | Description |
---|---|---|
message |
String
|
Error message to use instead of default. |
Validate uniqueness. Ensure the value for property is unique 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
|
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". |
ValidationError is raised when the application attempts to save an invalid model instance. Example:
{
"name": "ValidationError",
"status": 422,
"message": "The Model instance is not valid. \
See `details` property of the error object for more info.",
"statusCode": 422,
"details": {
"context": "user",
"codes": {
"password": [
"presence"
],
"email": [
"uniqueness"
]
},
"messages": {
"password": [
"can't be blank"
],
"email": [
"Email already exists"
]
}
},
}
You might run into situations where you need to raise a validation error yourself, for example in a "before" hook or a custom model method.
MyModel.prototype.preflight = function(changes, callback) {
// Update properties, do not save to db
for (var key in changes) {
model[key] = changes[key];
}
if (model.isValid()) {
return callback(null, { success: true });
}
// This line shows how to create a ValidationError
err = new ValidationError(model);
callback(err);
}
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 |
---|---|---|
result |
Boolean
|
True if no asynchronous validation is configured and all properties pass validation. |