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 It is an utility to define a property to the Object with info flags

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. This will mixin all of the data access object functions (DAO) into your modelClass definition.

Arguments
Name Type Description
modelClass Function

The model constructor that will be enhanced by DAO mixins.

dataSource.automigrate([models], [callback])

Drop schema objects such as tables, indexes, views, triggers, etc that correspond to model definitions attached to this DataSource instance, specified by the models parameter.

WARNING: In many situations, this will destroy data! autoupdate() will attempt to preserve data while updating the schema on your target DataSource, but this is not guaranteed to be safe.

Please check the documentation for your specific connector(s) for a detailed breakdown of behaviors for automigrate!

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

Model(s) to migrate. If not present, apply to all models.

[callback] Function

Callback function. Optional.

dataSource.autoupdate([models], [cb])

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

WARNING: autoupdate() will attempt to preserve data while updating the schema on your target DataSource, but this is not guaranteed to be safe.

Please check the documentation for your specific connector(s) for a detailed breakdown of behaviors for automigrate!*

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

Model(s) to migrate. If not present, apply to all models.

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

A Model class

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

Connect to the data source. If no callback is provided, it will return a Promise. Emits the 'connect' event.

Arguments
Name Type Description
callback
Returns
Name Type Description
result Promise

dataSource.createModel(className, properties, properties, settings)

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.

settings Object

A settings object that would typically be used for Model objects.

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 a property with name prop on a target model. See Properties for more information regarding valid options for params.

Arguments
Name Type Description
model String

Name of model

prop String

Name of property

params Property

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 connection to the DataSource.

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.

Returns
Name Type Description
result Promise

A Promise object that resolves with a map of model constructors, keyed by model name

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.

Returns
Name Type Description
result Object

A map of model constructors, keyed by model name

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

See Relations for more information.

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

Returns
Name Type Description
result Promise

A Promise with an array of exported foreign key relations.

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

See Relations for more information.

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

Returns
Name Type Description
result Promise

A Promise with an array of foreign key relations.

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
owner/schema String

The owner or schema to discover from.

all Boolean

If true, discover all models; if false, discover only models owned by the current user.

views Boolean

If true, include views; if false, only tables.

limit Number

Page size

offset Number

Starting index

Returns
Name Type Description
result Array.<ModelDefinition>

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 Array.<ModelDefinition>

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

See Properties for more details on the Property return type.

Arguments
Name Type Description
modelName String

The table/view name

options Object

The options

cb Function

Callback function. Optional

cb
options
Name Type Description
owner|schema String

The database owner or schema

Returns
Name Type Description
result Promise

A promise that returns an array of Properties (Property[])

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)

See ID Properties for more information.

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

Returns
Name Type Description
result Promise

A promise with an array of Primary Keys (Property[])

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 or schema

Returns
Name Type Description
result

dataSource.discoverSchema(tableName, [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
tableName String

The name of the table to discover.

[options] Object

An options object typically used for Relations. See Relations for more information.

[cb] Function

The callback function

Returns
Name Type Description
result Promise

A promise object that resolves to a single schema.

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

Discover schema from a given tableName/viewName.

Arguments
Name Type Description
tableName String

The table 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.

Returns
Name Type Description
result Promise

A promise object that resolves to an array of schemas.

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.

Returns
Name Type Description
result Array.<Object>

An array of schema definition objects.

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 To continuously add artifacts to datasource until it is frozen, but it is not really used in loopback.

dataSource.getModel()

See ModelBuilder.getModel for details.

dataSource.getModelDefinition()

See ModelBuilder.getModelDefinition See ModelBuilder.getModelDefinition for details.

dataSource.getOperation(operation)

Get an operation's metadata.

Arguments
Name Type Description
operation String

The operation name

dataSource.getTypes()

Get the data source types collection.

Returns
Name Type Description
result Array.<String>

The data source type array. For example, ['db', 'nosql', 'mongodb'] would be represent a datasource of type 'db', with a subtype of 'nosql', and would use the 'mongodb' connector.

Alternatively, ['rest'] would be a different type altogether, and would have no subtype.

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 or not migrations are required for the database schema to match the Model definitions attached to the DataSource. Note: This method applies only to SQL connectors.

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.

Returns
Name Type Description
result Boolean

Whether or not migrations are required.

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.ready(obj, args)

Check if the data source is ready. Returns a Boolean value.

Arguments
Name Type Description
obj Object

Deferred method call if the connector is not fully connected yet

args Object

argument passing to method call.

dataSource.supportTypes(types)

Check the data source supports the specified types.

Arguments
Name Type Description
types String or Array.<String>

Type name or an array of type names.

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.

Returns
Name Type Description
result String

The table name.

Class: ModelBaseClass(data, options)

Model class: base class for all persistent objects.

ModelBaseClass mixes Validatable and Hookable classes methods

Arguments
Name Type Description
data Object

Initial object data

options Object

An object to control the instantiation

Returns
Name Type Description
result ModelBaseClass

an instance of the ModelBaseClass

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

getMergePolicy() provides model merge policies to apply when extending a child model from a base model. Such a policy drives the way parent/child model properties/settings are merged/mixed-in together.

Below is presented the expected merge behaviour for each option. NOTE: This applies to top-level settings properties

  • Any

    • {replace: true} (default): child replaces the value from parent
    • assignin null on child setting deletes the inherited setting
  • Arrays:

    • {replace: false}: unique elements of parent and child cumulate
    • {rank: true} adds the model inheritance rank to array elements of type Object {} as internal property __rank
  • Object {}:

    • {replace: false}: deep merges parent and child objects
    • {patch: true}: child replaces inner properties from parent

The recommended built-in merge policy is as follows. It is returned by getMergePolicy() when calling the method with option {configureModelMerge: true}.

{
  description: {replace: true}, // string or array
  options: {patch: true}, // object
  hidden: {replace: false}, // array
  protected: {replace: false}, // array
  indexes: {patch: true}, // object
  methods: {patch: true}, // object
  mixins: {patch: true}, // object
  relations: {patch: true}, // object
  scope: {replace: true}, // object
  scopes: {patch: true}, // object
  acls: {rank: true}, // array
  // this setting controls which child model property's value allows deleting
  // a base model's property
  __delete: null,
  // this setting controls the default merge behaviour for settings not defined
  // in the mergePolicy specification
  __default: {replace: true},
}

The legacy built-in merge policy is as follows, it is retuned by getMergePolicy() when avoiding option configureModelMerge. NOTE: it also provides the ACLs ranking in addition to the legacy behaviour, as well as fixes for settings 'description' and 'relations': matching relations from child replace relations from parents.

{
  description: {replace: true}, // string or array
  properties: {patch: true}, // object
  hidden: {replace: false}, // array
  protected: {replace: false}, // array
  relations: {acls: true}, // object
  acls: {rank: true}, // array
}

getMergePolicy() can be customized using model's setting configureModelMerge as follows:

{
// ..
options: {
  configureModelMerge: {
    // merge options
  }
}
// ..
}

NOTE: mergePolicy parameter can also defined at JSON model definition root

getMergePolicy() method can also be extended programmatically as follows:

myModel.getMergePolicy = function(options) {
  const origin = myModel.base.getMergePolicy(options);
  return Object.assign({}, origin, {
    // new/overriding options
  });
};
Arguments
Name Type Description
options Object

option configureModelMerge can be used to alter the returned merge policy:

  • configureModelMerge: true will have the method return the recommended merge policy.
  • configureModelMerge: {..} will actually have the method return the provided object.
  • not providing this options will have the method return a merge policy emulating the the model merge behaviour up to datasource-juggler v3.6.1, as well as the ACLs ranking.
Returns
Name Type Description
result Object

mergePolicy The model merge policy to apply when using the current model as base class for a child model

ModelBaseClass.getPropertyType(propName)

Get model property type.

Arguments
Name Type Description
propName String

Property name

Returns
Name Type Description
result String

Name of property type

ModelBaseClass.isHiddenProperty(propertyName)

Checks if property is hidden.

Arguments
Name Type Description
propertyName String

Property name

Returns
Name Type Description
result Boolean

true or false if hidden or not.

ModelBaseClass.isProtectedProperty(propertyName)

Checks if property is protected.

Arguments
Name Type Description
propertyName String

Property name

Returns
Name Type Description
result Boolean

true or false if proptected or not.

ModelBaseClass.mixin(anotherClass, options)

Arguments
Name Type Description
anotherClass String

could be string or class. Name of the class or the class itself

options Object

An object to control the instantiation

Returns
Name Type Description
result ModelClass

ModelBaseClass.toString()

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

Class: ModelBaseClass Instance Methods

modelBaseClass.getPropertyType(propName)

Get model property type.

Arguments
Name Type Description
propName String

Property name

Returns
Name Type Description
result String

Name of property type

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, removeHidden, removeProtected)

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.

removeHidden Boolean

Boolean flag as part of the transformation. If true, then hidden properties should not be brought out.

removeProtected Boolean

Boolean flag as part of the transformation. If true, then protected properties should not be brought out.

Returns
Name Type Description
result Object

returns Plain JSON object

Class: DateString

DateString

A String whose value is a valid representation of a Date. Use this type if you need to preserve the format of the value and still check if it's valid. Example:

var loopback = require('loopback');
var dt = new loopback.DateString('2001-01-01');

dt.toString();
// '2001-01-01'
dt._date.toISOString();
// '2001-01-01T00:00:00.000Z'

You can use this definition on your models as well:

{
  "name": "Person",
  "base": "PersistedModel",
  "properties": {
    "name": {
      "type": "string"
    },
    "dob": {
      "type": "DateString",
      "required": true
    },
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}
Arguments
Name Type Description
value String

Class: DateString Instance Methods

dateString.toJSON()

Returns the JSON representation of the DateString object.

Returns
Name Type Description
result String

A JSON string.

dateString.toString()

Returns the value of DateString in its original form.

Returns
Name Type Description
result String

The Date as a String.

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.

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

findWithForeignKeysByPage(model, filter, fkName, pageSize, options, cb)

Find related items with an array of foreign keys by page

Arguments
Name Type Description
model

The model class

filter

The query filter

fkName

The name of the foreign key property

pageSize

The size of page

options

Options

cb

findWithForeignKeysByPage()

1st DB Call of 2 step process. Get through model objects first

findWithForeignKeysByPage()

2nd DB Call of 2 step process. Get modelTo (target) objects

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

includeHasManyThrough(callback)

Handle inclusion of HasManyThrough/HasAndBelongsToMany/Polymorphic HasManyThrough relations

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

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, subClassProperties, subClassSettings)

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.

subClassProperties Object

child model properties, added to base model properties.

subClassSettings Object

child model settings such as relations and acls, merged with base model settings.

mergeSettings(baseClassSettings, subClassSettings, mergePolicy)

Merge parent and child model settings according to the provided merge policy.

Below is presented the expected merge behaviour for each option of the policy. NOTE: This applies to top-level settings properties

  • Any

    • {replace: true} (default): child replaces the value from parent
    • assignin null on child setting deletes the inherited setting
  • Arrays:

    • {replace: false}: unique elements of parent and child cumulate
    • {rank: true} adds the model inheritance rank to array elements of type Object {} as internal property __rank
  • Object {}:

    • {replace: false}: deep merges parent and child objects
    • {patch: true}: child replaces inner properties from parent

Here is an example of merge policy:

{
  description: {replace: true}, // string or array
  properties: {patch: true}, // object
  hidden: {replace: false}, // array
  protected: {replace: false}, // array
  relations: {acls: true}, // object
  acls: {rank: true}, // array
}
Arguments
Name Type Description
baseClassSettings Object

parent model settings.

subClassSettings Object

child model settings.

mergePolicy Object

merge policy, as defined in ModelClass.getMergePolicy()

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:

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

nullCheck(attr, conf, err)

Checks if attribute is undefined or null. Calls err function with 'blank' or 'null'. See defaultMessages. You can affect this behaviour with conf.allowBlank and conf.allowNull.

Arguments
Name Type Description
attr String

Property name of attribute

conf Object

conf object for validator

err Function

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

allowNull Boolean

Whether null values are allowed.

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

allowNull Boolean

Whether null values are allowed.

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
in Array

Property must not match any of the values in the array to be valid.

message String

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

allowNull Boolean

Whether null values are allowed.

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.validatesFormatOf('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".

allowNull Boolean

Whether null values are allowed.

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

See below

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

allowNull Boolean

Whether null values are allowed.

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

allowNull Boolean

Whether null values are allowed.

ignoreCase String

Make the validation case insensitive

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
  var err = new MyModel.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.