Class: Define new DataSource

Define new DataSource

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

Type of dataSource connector (mysql, mongoose, oracle, redis)

settings Object

Database-specific settings to establish connection (settings depend on specific connector). See above.

Class: Define new 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: Define new 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(Models, cb)

Drop each model table and re-create. This method applies only to SQL connectors.

Arguments
Name Type Description
Models String

to be migrated, if not present, apply to all models. This can also be an array of Strings.

cb Function

Callback function. Optional. WARNING: Calling this function will cause all data to be lost! Use autoupdate if you need to preserve data.

dataSource.autoupdate(Models, [cb])

Update existing database tables. This method make sense only for sql connectors.

Arguments
Name Type Description
Models String

to be migrated, if not present, apply to all models. This can also be an array of Strings.

[cb] Function

The callback function

dataSource.columnMetadata(modelName, propertyName)

Return column metadata for specified modelName and propertyName

Arguments
Name Type Description
modelName String

The model name

propertyName

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

The property name

Returns
Name Type Description
result String

columnName

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, settings)

Define a model class. 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 class properties in format {property: Type, property2: Type2, ...} or {property: {type: Type}, property2: {type: Type2}, ...}

settings Object

Other configuration settings.

Returns
Name Type Description
result

newly created class

dataSource.defineForeignKey(className, key, foreignClassName)

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

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 Fucntion

The callback function. Optional.

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

Discover and build models from the given owner/modelName

options

 {String} owner/schema - The database owner/schema name
 {Boolean} relations - If relations (primary key/foreign key) are navigated
 {Boolean} all - If all owners are included
 {Boolean} views - If views are included
Arguments
Name Type Description
modelName String

The model name

[options] Object

The options

[cb] Function

The callback function

dataSource.discoverAndBuildModelsSync(modelName, [options])

Discover and build models from the given owner/modelName synchronously

options

 {String} owner/schema - The database owner/schema name
 {Boolean} relations - If relations (primary key/foreign key) are navigated
 {Boolean} all - If all owners are included
 {Boolean} views - If views are included
Arguments
Name Type Description
modelName String

The model name

[options] Object

The options

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). They are ordered by fkTableOwner, fkTableName, and keySeq.

foreign key 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

options

 owner/schema The database owner/schema
Arguments
Name Type Description
modelName String

The model name

options Object

The options

[cb] Function

The callback function

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

foreign key 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

options

 owner/schema The database owner/schema
Arguments
Name Type Description
modelName String

The model name

options Object

The options

[cb] Function

The callback function

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)

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

Kyes in options object:

  • all: true - Discovering all models, false - Discovering the models owned by the current user
  • views: true - Including views, false - only tables
  • limit: The page size
  • offset: The starting index
Arguments
Name Type Description
options Object

The options

Callback Function

function. Optional.

dataSource.discoverModelDefinitionsSync(options)

The synchronous version of discoverModelDefinitions

Arguments
Name Type Description
options Object

The options

Returns
Name Type Description
result

dataSource.discoverModelProperties(modelName, options, cb)

Discover properties for a given model.

property description:

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

Options:

  • owner/schema The database owner/schema
Arguments
Name Type Description
modelName String

The table/view name

options Object

The options

cb Function

Callback function. Optional

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.

Each primary key column description has the following columns:

  • owner {String} => table schema (may be null)
  • tableName {String} => table name
  • columnName {String} => column name
  • keySeq {Number} => sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2 would represent the second column within the primary key).
  • pkName {String} => primary key name (may be null)

The owner defaults to current user.

Options:

  • owner/schema The database owner/schema
Arguments
Name Type Description
modelName String

The model name

options Object

The options

[cb] Function

The callback function

dataSource.discoverPrimaryKeysSync(modelName, options)

The synchronous version of discoverPrimaryKeys

Arguments
Name Type Description
modelName String

The model name

options Object

The options

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

options

 {String} owner/schema - The database owner/schema name
 {Boolean} relations - If relations (primary key/foreign key) are navigated
 {Boolean} all - If all owners are included
 {Boolean} views - If views are included
Arguments
Name Type Description
modelName String

The model name

[options] Object

The options

[cb] Function

The callback function

dataSource.discoverSchemasSync(modelName, [options])

Discover schema from a given table/view synchronously

options

 {String} owner/schema - The database owner/schema name
 {Boolean} relations - If relations (primary key/foreign key) are navigated
 {Boolean} all - If all owners are included
 {Boolean} views - If views are included
Arguments
Name Type Description
modelName String

The model name

[options] Object

The options

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.isActual([models])

Check whether migrations needed This method make sense only for sql connectors.

Arguments
Name Type Description
[models] 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.mixin(ModelCtor)

Mixin DataAccessObject methods.

Arguments
Name Type Description
ModelCtor Function

The model constructor

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

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

Arguments
Name Type Description
obj

{Object} ?

args

{Object} ?

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

GeoPoint

The GeoPoint object represents a physical location.

For example:

var here = new 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
latlong Object

Object with two Number properties: lat and long.

Class Properties
Name Type Description
lat Number
lng Number

Class: GeoPoint Static Methods

GeoPoint.distanceBetween(pointA, pointB, options)

Determine the spherical distance between two GeoPoints. Specify units of measurement with the 'type' property in options object. Type can be:

  • miles (default)
  • radians
  • kilometers
  • meters
  • miles
  • feet
  • degrees
Arguments
Name Type Description
pointA GeoPoint

Point A

pointB GeoPoint

Point B

options Object

Options object; has one key, 'type', to specify the units of measurment (see above). Default is miles.

Class: GeoPoint Instance Methods

geoPoint.distanceTo(point, options)

Determine the spherical distance to the given point. Example:

var here = new GeoPoint({lat: 10, lng: 10});
var there = new GeoPoint({lat: 5, lng: 5});
GeoPoint.distanceBetween(here, there, {type: 'miles'}) // 438
Arguments
Name Type Description
point Object

GeoPoint object to which to measure distance.

options Object

Use type key to specify units of measurment (default is miles).

geoPoint.toString()

Simple serialization.

Class: DataAccessObject

DataAccessObject

Base class for all persistent objects. Provides a common API to access any database connector. This class describes only abstract behavior. Refer to the specific connector (lib/connectors/*.js) for details.

DataAccessObject mixes Inclusion classes methods.

Arguments
Name Type Description
data Object

Initial object data

Class: DataAccessObject Static Methods

DataAccessObject.count(where, cb)

Return count of matched records

Arguments
Name Type Description
where Object

Search conditions (optional)

cb Function

Callback, called with (err, count)

DataAccessObject.create(data, callback)

Create new instance of Model class, saved in database. The callback function is called with arguments:

  • err (null or Error)
  • instance (null or Model)
Arguments
Name Type Description
data

{Object} Optional data object

callback

{Function} Callback function

DataAccessObject.exists(id, cb)

Check whether a model instance exists in database

Arguments
Name Type Description
id id

Identifier of object (primary key value)

cb Function

Callback function called with (err, exists: Bool)

DataAccessObject.find([query], params, callback)

Find all instances of Model, matched by query make sure you have marked as index: true fields for filter or sort

Arguments
Name Type Description
[query] Object

the query object

  • where: Object { key: val, key2: {gt: 'val2'}}
  • include: String, Object or Array. See DataAccessObject.include().
  • order: String
  • limit: Number
  • skip: Number
params Object

(optional)

callback Function

(required) called with two arguments: err (null or Error), array of instances

DataAccessObject.findById(id, cb)

Find object by id

Arguments
Name Type Description
id

Primary key value

cb Function

Callback called with (err, instance)

DataAccessObject.findOne(query, cb)

Find one record, same as all, limited by 1 and return object, not collection

Arguments
Name Type Description
query Object

search conditions: {where: {test: 'me'}}

cb Function

callback called with (err, instance)

DataAccessObject.findOrCreate(query, data, cb)

Find one record, same as all, limited by 1 and return object, not collection, if not found, create using data provided as second argument

Arguments
Name Type Description
query Object

Search conditions: {where: {test: 'me'}}.

data Object

Object to create.

cb Function

Callback called with (err, instance)

DataAccessObject.remove([where], [cb])

Destroy all matching records

Arguments
Name Type Description
[where] Object

An object that defines the criteria

[cb] Function

Callback called with (err)

DataAccessObject.removeById(id, cb)

Destroy a record by id

Arguments
Name Type Description
id

The id value

cb Function

Callback called with (err)

DataAccessObject.scope(name, query, [targetClass])

Define a scope for the model class. Scopes enable you to specify commonly-used queries that you can reference as method calls on a model.

Arguments
Name Type Description
name String

The scope name

query Object

The query object for DataAccessObject.find()

[targetClass] ModelClass

The model class for the query, default to the declaring model

DataAccessObject.upsert(data, callback)

Update or insert a model instance.

Arguments
Name Type Description
data Object

The model instance data

callback Function

The callback function (optional).

Class: DataAccessObject Instance Methods

dataAccessObject.reload(callback)

Reload object from persistence Requires id member of object to be able to call find

Arguments
Name Type Description
callback Function

Called with (err, instance) arguments

dataAccessObject.save(options, callback(err,)

Save instance. When instance haven't id, create method called instead. Triggers: validate, save, update | create

Arguments
Name Type Description
options

{validate: true, throws: false} [optional]

callback(err,

obj)

dataAccessObject.updateAttribute(name, value, callback)

Update single attribute

equals to `updateAttributes({name: value}, cb)

Arguments
Name Type Description
name String

Name of property

value Mixed

Value of property

callback Function

Callback function called with (err, instance)

dataAccessObject.updateAttributes(data, callback)

Update set of attributes

this method performs validation before updating

Arguments
Name Type Description
data Object

Data to update

callback Function

Callback function called with (err, instance)

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

Checks is property changed based on current property and initial value

Arguments
Name Type Description
propertyName String

Property name

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: ModelBuilder()

ModelBuilder - A builder to define data models.

Class: ModelBuilder Static Methods

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)

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

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.extendModel(model, props)

Extend existing model with bunch of properties

Example: Instead of doing amending the content model with competition attributes like this:

    db.defineProperty('Content', 'competitionType', { type: String });
    db.defineProperty('Content', 'expiryDate', { type: Date, index: true });
    db.defineProperty('Content', 'isExpired', { type: Boolean, index: true });

The extendModel() method enables you to extend the content model with competition attributes.

    db.extendModel('Content', {
      competitionType: String,
      expiryDate: { type: Date, index: true },
      isExpired: { type: Boolean, index: true }
    });
Arguments
Name Type Description
model String

Name of model

props Object

Hash of properties

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 {*} 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: Inclusion()

Inclusion - Model mixin.

Class: Inclusion Static Methods

Inclusion.include(objects, {String},, 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

{String},

{Object} or {Array} include Which relations to load.

cb Function

Callback called when relations are loaded

Class: Relation

Relation

Relations class

Class: Relation Static Methods

scopeMethods.add({Object|ID) acInst The actual instance or id value)

Add the target model instance to the 'hasMany' relation

Arguments
Name Type Description
{Object|ID) acInst The actual instance or id value

Relation.belongsTo(anotherClass, params)

Declare "belongsTo" relation.

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
anotherClass Class

Class to belong

params Object

Configuration {as: 'propertyName', foreignKey: 'keyName'}

Relation.hasMany(anotherClass, params)

Declare "hasMany" relation. Example: User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});

Arguments
Name Type Description
anotherClass Relation

Class to has many

params Object

Configuration {as:, foreignKey:}

Relation.relationNameFor(foreignKey)

Find the relation by foreign key

Arguments
Name Type Description
foreignKey

The foreign key

Returns
Name Type Description
result Object

The relation object

scopeMethods.remove({Object|ID) acInst The actual instance or id value)

Remove the target model instance from the 'hasMany' relation

Arguments
Name Type Description
{Object|ID) acInst The actual instance or id value

Class: Validatable

Validatable

Validation mixins for LoopBack models.

This class provides methods that add validation cababilities to models. Each of this validations run when obj.isValid() method called.

Each configurator can accept n params (n-1 field names and one config). Config is {Object} depends on specific validation, but all of them has one common part: message member. It can be just string, when only one situation possible, e.g. Post.validatesPresenceOf('title', { message: 'can not be blank' });

In more complicated cases it can be {Hash} of messages (for each case): User.validatesLengthOf('password', { min: 6, max: 20, message: {min: 'too short', max: 'too long'}});

Class: Validatable Static Methods

validateCustom()

Custom validator

validateExclusion()

Exclusion validator

validateFormat()

Format validator

validateInclusion()

Inclusion validator

validateLength()

Length validator

validateNumericality()

Numericality validator

validatePresence()

Presence validator

validateUniqueness()

Uniqueness validator

Class: Validatable Instance Methods

validatable.isValid(callback)

This method performs validation, triggers validation hooks. Before validation obj.errors collection cleaned. Each validation can add errors to obj.errors collection. If collection is not blank, validation failed.

Arguments
Name Type Description
callback Function

called with (valid)