Class: DataSource

DataSource

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
});
Arguments
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.

settings
Name Type Description
connector String

Database connector to use. For any supported connector, can be any of:

  • The connector module from require(connectorName).
  • The full name of the connector module, such as 'loopback-connector-oracle'.
  • The short name of the connector module, such as 'oracle'.
  • A local module under ./connectors/ folder.
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.

Class: DataSource Static Methods

defineReadonlyProp(obj, key, value)

Define readonly property on object

Arguments
Name Type Description
obj Object

The property owner

key String

The property name

value Mixed

The default value

hiddenProperty(obj, key, value)

Define a hidden property

Arguments
Name Type Description
obj Object

The property owner

key String

The property name

value Mixed

The default value

Class: DataSource Instance Methods

dataSource.attach(modelClass)

Attach an existing model to a data source.

Arguments
Name Type Description
modelClass Function

The model constructor

dataSource.automigrate(model, [callback])

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.

Arguments
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.

dataSource.autoupdate(model, [cb])

Update existing database tables. This method applies only to database connectors.

Arguments
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

dataSource.buildModelFromInstance(name, json, options)

Introspect a JSON object and build a model class

Arguments
Name Type Description
name String

Name of the model

json Object

The json object representing a model instance

options Object

Options

Returns
Name Type Description
result

dataSource.columnMetadata(modelName, propertyName)

Return column metadata for specified modelName and propertyName

Arguments
Name Type Description
modelName String

The model name

propertyName String

The property name

Returns
Name Type Description
result Object

column metadata

dataSource.columnName(modelName, propertyName)

Return column name for specified modelName and propertyName

Arguments
Name Type Description
modelName String

The model name

propertyName String

The property name

Returns
Name Type Description
result String

columnName The column name.

dataSource.columnNames(modelName)

Return column names for specified modelName

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Array.<String>

column names

dataSource.createModel(className, properties, properties)

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}
      ]
    });
Arguments
Name Type Description
className String

Name of the model to create.

properties Object

Hash of model properties in format {property: Type, property2: Type2, ...} or {property: {type: Type}, property2: {type: Type2}, ...}

properties Object

Other configuration options. This corresponds to the options key in the config object.

dataSource.defineForeignKey(className, key, foreignClassName, pkName)

Define foreign key to another model

Arguments
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

dataSource.defineOperation(name, options, fn)

Define an operation to the data source

Arguments
Name Type Description
name String

The operation name

options Object

The options

fn Function

The function

dataSource.defineProperty(model, prop, params)

Define single property named prop on model

Arguments
Name Type Description
model String

Name of model

prop String

Name of property

params Object

Property settings

dataSource.disableRemote(operation)

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:

  • Disabled operations will not be added to attached models.
  • Disabling the remoting for a method only affects client access (it will still be available from server models).
  • Data sources must enable / disable operations before attaching or creating models.
Arguments
Name Type Description
operation String

The operation name

dataSource.disconnect([cb])

Close database connection

Arguments
Name Type Description
[cb] Function

The callback function. Optional.

dataSource.discoverAndBuildModels(modelName, [options], [cb])

Discover and build models from the specified owner/modelName.

Arguments
Name Type Description
modelName String

The model name.

[options] Object

Options; see below.

[cb] Function

The callback function

[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.

dataSource.discoverAndBuildModelsSync(modelName, [options], modelName, [options])

Discover and build models from the given owner/modelName synchronously.

Arguments
Name Type Description
modelName String

The model name.

[options] Object

Options; see below.

modelName String

The model name

[options] Object

The options

[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.

dataSource.discoverExportedForeignKeys(modelName, options, [cb])

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
Arguments
Name Type Description
modelName String

The model name

options Object

The options

[cb] Function

The callback function

options
Name Type Description
owner|schema String

The database owner or schema

dataSource.discoverExportedForeignKeysSync(modelName, options)

The synchronous version of discoverExportedForeignKeys

Arguments
Name Type Description
modelName String

The model name

options Object

The options

Returns
Name Type Description
result

dataSource.discoverForeignKeys(modelName, options, [cb])

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
Arguments
Name Type Description
modelName String

The model name

options Object

The options

[cb] Function

The callback function

options
Name Type Description
owner|schema String

The database owner or schema

dataSource.discoverForeignKeysSync(modelName, options)

The synchronous version of discoverForeignKeys

Arguments
Name Type Description
modelName String

The model name

options Object

The options

Returns
Name Type Description
result

dataSource.discoverModelDefinitions(options, Callback, options)

Discover existing database tables. This method returns an array of model objects, including {type, name, onwer}

Arguments
Name Type Description
options Object

The options

Callback Function

function. Optional.

options Object

Discovery options. See below.

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

dataSource.discoverModelDefinitionsSync(options)

The synchronous version of discoverModelDefinitions.

Arguments
Name Type Description
options Object

The options

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

Returns
Name Type Description
result

dataSource.discoverModelProperties(modelName, options, cb)

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
Arguments
Name Type Description
modelName String

The table/view name

options Object

The options

cb Function

Callback function. Optional

options
Name Type Description
owner|schema String

The database owner or schema

dataSource.discoverModelPropertiesSync(modelName, options)

The synchronous version of discoverModelProperties

Arguments
Name Type Description
modelName String

The table/view name

options Object

The options

Returns
Name Type Description
result

dataSource.discoverPrimaryKeys(modelName, options, [cb])

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)
Arguments
Name Type Description
modelName String

The model name

options Object

The options

[cb] Function

The callback function

options
Name Type Description
owner|schema String

The database owner or schema

dataSource.discoverPrimaryKeysSync(modelName, options)

The synchronous version of discoverPrimaryKeys

Arguments
Name Type Description
modelName String

The model name

options Object

The options

options
Name Type Description
owner|schema String

The database owner orschema

Returns
Name Type Description
result

dataSource.discoverSchema(modelName, [options], [cb])

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"
          }
        }
      }
    }
Arguments
Name Type Description
modelName String

The model name

[options] Object

The options

[cb] Function

The callback function

dataSource.discoverSchemas(modelName, [options], [cb])

Discover schema from a given modelName/view.

Arguments
Name Type Description
modelName String

The model name.

[options] Object

Options; see below.

[cb] Function

The callback function

[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.

dataSource.discoverSchemasSync(modelName, [options])

Discover schema from a given table/view synchronously

Arguments
Name Type Description
modelName String

The model name

[options] Object

Options; see below.

[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.

dataSource.enableRemote(operation)

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().

Arguments
Name Type Description
operation String

The operation name

dataSource.freeze()

Freeze dataSource. Behavior depends on connector

dataSource.getModel()

See ModelBuilder.getModel

dataSource.getModelDefinition()

See ModelBuilder.getModelDefinition

dataSource.getOperation(operation)

Get an operation's metadata.

Arguments
Name Type Description
operation String

The operation name

dataSource.getTypes()

Get the data source types

Returns
Name Type Description
result Array.<String>

The data source type, such as ['db', 'nosql', 'mongodb'], ['rest'], or ['db', 'rdbms', 'mysql']

dataSource.idColumnName(modelName)

Find the ID column name

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result String

columnName for ID

dataSource.idName(modelName)

Find the ID property name

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result String

property name for ID

dataSource.idNames(modelName)

Find the ID property names sorted by the index

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Array.<String>

property names for IDs

dataSource.idProperty(modelName)

Find the id property definition

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Object

The id property definition

dataSource.isActual([models])

Check whether migrations needed This method applies only to SQL connectors.

Arguments
Name Type Description
[models] String or Array.<String>

A model name or an array of model names. If not present, apply to all models.

dataSource.isRelational()

Check if the backend is a relational DB

Returns
Name Type Description
result Boolean

dataSource.operations()

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
 },
 ...
}

dataSource.ping([cb])

Ping the underlying connector to test the connections

Arguments
Name Type Description
[cb] Function

Callback function

dataSource.supportTypes(types)

Check the data source supports the specified types.

Arguments
Name Type Description
types String

Type name or an array of type names. Can also be array of Strings.

Returns
Name Type Description
result Boolean

true if all types are supported by the data source

dataSource.tableName(modelName)

Return table name for specified modelName

Arguments
Name Type Description
modelName String

The model name

Class: ModelBaseClass(data)

Model class: base class for all persistent objects.

ModelBaseClass mixes Validatable and Hookable classes methods

Arguments
Name Type Description
data Object

Initial object data

Class: ModelBaseClass Static Methods

ModelBaseClass.defineProperty(prop, params)

Define a property on the model.

Arguments
Name Type Description
prop String

Property name

params Object

Various property configuration

ModelBaseClass.toString()

Return string representation of class This overrides the default toString() method

Class: ModelBaseClass Instance Methods

modelBaseClass.reset()

Reset dirty attributes. This method does not perform any database operations; it just resets the object to its initial state.

modelBaseClass.toObject(onlySchema)

Convert model instance to a plain JSON object. Returns a canonical object representation (no getters and setters).

Arguments
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.

Class: GeoPoint

GeoPoint

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, ...]
});
Arguments
Name Type Description
Options Object

Object with two Number properties: lat and long.

Options Array

Array with two Number entries: [lat,long].

Options
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.

Options
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.

Class Properties
Name Type Description
lat Number

The latitude in degrees.

lng Number

The longitude in degrees.

Class: GeoPoint Static Methods

GeoPoint.distanceBetween(pointA, pointB, options)

Determine the spherical distance between two GeoPoints.

Arguments
Name Type Description
pointA GeoPoint

Point A

pointB GeoPoint

Point B

options Object

Options object with one key, 'type'. See below.

options
Name Type Description
type String

Unit of measurement, one of:

  • miles (default)
  • radians
  • kilometers
  • meters
  • miles
  • feet
  • degrees

Class: GeoPoint Instance Methods

geoPoint.distanceTo(point, options)

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
Arguments
Name Type Description
point Object

GeoPoint object to which to measure distance.

options Object

Options object with one key, 'type'. See below.

options
Name Type Description
type String

Unit of measurement, one of:

  • miles (default)
  • radians
  • kilometers
  • meters
  • miles
  • feet
  • degrees

geoPoint.toString()

Simple serialization.

Class: Hookable

Hookable

Hooks object.

idName(m)

Find the idKey of a Model.

Arguments
Name Type Description
m ModelConstructor

Model Constructor

Returns
Name Type Description
result String

execTasksWithInterLeave(tasks, callback)

Utility Function to allow interleave before and after high computation tasks

Arguments
Name Type Description
tasks
callback

Class: Inclusion()

Inclusion - Model mixin.

Class: Inclusion Static Methods

if()

call relation specific include functions

Inclusion.include(objects, include, [options], cb)

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']});

Arguments
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

includeHasMany(callback)

Handle inclusion of HasMany relation

Arguments
Name Type Description
callback

includeHasManyThrough(callback)

Handle inclusion of HasManyThrough/HasAndBelongsToMany/Polymorphic HasManyThrough relations

Arguments
Name Type Description
callback

includePolymorphicBelongsTo(callback)

Handle Inclusion of Polymorphic BelongsTo relation

Arguments
Name Type Description
callback

includeReferencesMany(callback)

Handle inclusion of ReferencesMany relation

Arguments
Name Type Description
callback

processPolymorphicType(modelType, callback)

Process Polymorphic objects of each type (modelType)

Arguments
Name Type Description
modelType String
callback

setIncludeData(result, cb)

Sets the related objects as a property of Parent Object

Arguments
Name Type Description
result Array.<Model> or Model

Related Object/Objects

cb

targetFetchHandler(err, targets)

Process fetched related objects

Arguments
Name Type Description
err
targets Array.<Model>
Returns
Name Type Description
result

targetFetchHandler(err, {Array<Model>}targets)

Handle the fetched target objects

Arguments
Name Type Description
err
{Array<Model>}targets
Returns
Name Type Description
result

throughFetchHandler(err, throughObjs)

Handle the results of Through model objects and fetch the modelTo items

Arguments
Name Type Description
err
throughObjs Array.<Model>
Returns
Name Type Description
result

Class: ModelBuilder()

ModelBuilder - A builder to define data models.

Class Properties
Name Type Description
definitions Object

Definitions of the models.

models Object

Model constructors

Class: ModelBuilder Static Methods

ModelClass.extend(className, properties, settings)

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);
Arguments
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.

ModelClass.registerProperty(propertyName)

Register a property for the model class

Arguments
Name Type Description
propertyName String

Name of the property.

Class: ModelBuilder Instance Methods

modelBuilder.buildModelFromInstance(name, json, options)

Introspect the JSON document to build a corresponding model.

Arguments
Name Type Description
name String

The model name

json Object

The JSON object

options Object

The options

Returns
Name Type Description
result

{}

modelBuilder.buildModels(schemas)

Build models from schema definitions

schemas can be one of the following:

  1. An array of named schema definition JSON objects
  2. A schema definition JSON object
  3. A list of property definitions (anonymous)
Arguments
Name Type Description
schemas

The schemas

Returns
Name Type Description
result Object

A map of model constructors keyed by model name

modelBuilder.define(className, properties, settings, parent)

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 }
});
Arguments
Name Type Description
className String

Name of class

properties Object

Hash of class properties in format {property: Type, property2: Type2, ...} or {property: {type: Type}, property2: {type: Type2}, ...}

settings Object

Other configuration of class

parent Function

Parent model

modelBuilder.defineProperty(model, propertyName, propertyDefinition)

Define single property named propertyName on model

Arguments
Name Type Description
model String

Name of model

propertyName String

Name of property

propertyDefinition Object

Property settings

modelBuilder.defineValueType(type, aliases)

Define a new value type that can be used in model schemas as a property type.

Arguments
Name Type Description
type function()

Type constructor.

aliases Array.<string>

Optional list of alternative names for this type.

modelBuilder.extendModel(model, properties)

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 }
    });
Arguments
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 propertyName: {options} where the options are described below.

properties
Name Type Description
type String

Datatype of property: Must be an LDL type.

index Boolean

True if the property is an index; false otherwise.

modelBuilder.getModel(name, forceCreate)

Get a model by name.

Arguments
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.

Returns
Name Type Description
result

The model class

modelBuilder.getModelDefinition(name)

Get the model definition by name

Arguments
Name Type Description
name String

The model name

Returns
Name Type Description
result ModelDefinition

The model definition

modelBuilder.getSchemaName()

Get the schema name

modelBuilder.resolveType(type)

Resolve the type string to be a function, for example, 'String' to String. Returns {Function} if the type is resolved

Arguments
Name Type Description
type String

The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive

Class: RelationMixin

RelationMixin

RelationMixin class. Use to define relationships between models.

Class: RelationMixin Static Methods

RelationMixin.belongsTo(modelTo, params)

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.

Arguments
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.

params
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.

RelationMixin.hasAndBelongsToMany(modelTo, params)

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);
Arguments
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.

params
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

RelationMixin.hasMany(modelTo, parameters)

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);
  });
});
Arguments
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.

parameters
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

Class: ObserverMixin

ObserverMixin

ObserverMixin class. Use to add observe/notifyObserversOf APIs to other classes.

Class: ObserverMixin Static Methods

ObserverMixin.clearObservers(operation)

Unregister all asynchronous observers for the given operation (event).

Arguments
Name Type Description
operation String

The operation name.

ObserverMixin.notifyObserversAround(operation, context, fn, callback)

Run the given function with before/after observers. It's done in three serial steps asynchronously:

  • Notify the registered observers under 'before ' + operation
  • Execute the function
  • Notify the registered observers under 'after ' + operation

If an error happens, it fails fast and calls the callback with err.

Arguments
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

Returns
Name Type Description
result

ObserverMixin.notifyObserversOf(operation, context, callback)

Invoke all async observers for the given operation(s).

Arguments
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.

ObserverMixin.observe(operation, listener)

Register an asynchronous observer for the given operation (event).

Arguments
Name Type Description
operation String

The operation name.

listener function

The listener function. It will be invoked with this set to the model constructor, e.g. User.

Callback
Name Type Description
context Object

Operation-specific context.

next function(Error|undefined)

The callback to call when the observer has finished.

ObserverMixin.removeObserver(operation, listener)

Unregister an asynchronous observer for the given operation (event).

Arguments
Name Type Description
operation String

The operation name.

listener function

The listener function.

Class: TransactionMixin

TransactionMixin

TransactionMixin class. Use to add transaction APIs to a model class.

Class: TransactionMixin Static Methods

TransactionMixin.beginTransaction([options], cb)

Begin a new transaction

Arguments
Name Type Description
[options] Object or String

Options can be one of the forms: - Object: {isolationLevel: '...', timeout: 1000}

  • String: isolationLevel

Valid values of isolationLevel are:

  • Transaction.READ_COMMITTED = 'READ COMMITTED'; // default
  • Transaction.READ_UNCOMMITTED = 'READ UNCOMMITTED';
  • Transaction.SERIALIZABLE = 'SERIALIZABLE';
  • Transaction.REPEATABLE_READ = 'REPEATABLE READ';
cb Function

Callback function. It calls back with (err, transaction). 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) {...});
    });
  });
});

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.

Class: TransactionMixin Instance Methods

transaction.commit(cb)

Commit a transaction and release it back to the pool

Arguments
Name Type Description
cb Function

Callback function

Returns
Name Type Description
result Promise

transaction.rollback(cb)

Rollback a transaction and release it back to the pool

Arguments
Name Type Description
cb Function

Callback function

Returns
Name Type Description
result Promise

Class: Validatable

Validatable

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'}});

Class: Validatable Static Methods

Validatable.validate(propertyName, validatorFn, Options)

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
Arguments
Name Type Description
propertyName String

Property name to validate.

validatorFn Function

Custom validation function.

Options Object

See below.

Options
Name Type Description
message String

Optional error message if property is not valid. Default error message: " is invalid".

Validatable.validateAsync(propertyName, validatorFn, Options)

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
    })
Arguments
Name Type Description
propertyName String

Property name to validate.

validatorFn Function

Custom validation function.

Options Object

See below

Options
Name Type Description
message String

Optional error message if property is not valid. Default error message: " is invalid".

Validatable.validatesAbsenceOf(propertyName, errMsg)

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' });
Arguments
Name Type Description
propertyName String

One or more property names.

errMsg Object

Optional custom error message. Default is "can't be set"

errMsg
Name Type Description
message String

Error message to use instead of default.

Validatable.validatesExclusionOf(propertyName, Options)

Validate exclusion. Require a property value not be in the specified array.

Example: Company.validatesExclusionOf('domain', {in: ['www', 'admin']});

Arguments
Name Type Description
propertyName String

Property name to validate.

Options Object
Options
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".

Validatable.validatesFormatOf(propertyName, Options)

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+/});

Arguments
Name Type Description
propertyName String

Property name to validate.

Options Object
Options
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".

Validatable.validatesInclusionOf(propertyName, Options)

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'
});
Arguments
Name Type Description
propertyName String

Property name to validate.

Options Object
Options
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".

Validatable.validatesLengthOf(propertyName, Options)

Validate length. Require a property length to be within a specified range. Three kinds of validations: min, max, is.

Default error messages:

  • min: too short
  • max: too long
  • is: length is wrong

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'}});
Arguments
Name Type Description
propertyName String

Property name to validate.

Options Object

See below.

Options
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

Validatable.validatesNumericalityOf(propertyName, Options)

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: '...' }});
Arguments
Name Type Description
propertyName String

Property name to validate.

Options Object

See below.

Options
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:

  • number: is not a number
  • int: is not an integer

Validatable.validatesPresenceOf(propertyName, errMsg)

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'});
Arguments
Name Type Description
propertyName String

One or more property names.

errMsg Object

Optional custom error message. Default is "can't be blank"

errMsg
Name Type Description
message String

Error message to use instead of default.

Validatable.validatesUniquenessOf(propertyName, Options)

Validate uniqueness. Ensure the value for property is unique in the collection of models. Not available for all connectors. Currently supported with these connectors:

  • In Memory
  • Oracle
  • MongoDB
// 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'] });
Arguments
Name Type Description
propertyName String

Property name to validate.

Options Object

See below.

Options
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()

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);
}

Class: Validatable Instance Methods

validatable.isValid(callback)

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: ...
        // => }
    }
});
Arguments
Name Type Description
callback Function

called with (valid)

Returns
Name Type Description
result Boolean

True if no asynchronous validation is configured and all properties pass validation.