var app = loopback()

LoopBackApplication

The App object represents a Loopback application.

The App object extends Express and supports Express middleware. See Express documentation for details.

var loopback = require('loopback');
var app = loopback();

app.get('/', function(req, res){
  res.send('hello world');
});

app.listen(3000);

Class: LoopBackApplication Static Methods

app.connector(name, connector)

Register a connector.

When a new data-source is being added via app.dataSource, the connector name is looked up in the registered connectors first.

Connectors are required to be explicitly registered only for applications using browserify, because browserify does not support dynamic require, which is used by LoopBack to automatically load the connector module.

Arguments
Name Type Description
name String

Name of the connector, e.g. 'mysql'.

connector Object

Connector object as returned by require('loopback-connector-{name}').

app.dataSource(name, config)

Define a DataSource.

Arguments
Name Type Description
name String

The data source name

config Object

The data source config

app.enableAuth()

Enable app wide authentication.

app.listen([cb])

Listen for connections and update the configured port.

When there are no parameters or there is only one callback parameter, the server will listen on app.get('host') and app.get('port').

For example, to listen on host/port configured in app config:

app.listen();

Otherwise all arguments are forwarded to http.Server.listen.

For example, to listen on the specified port and all hosts, and ignore app config.

app.listen(80);

The function also installs a listening callback that calls app.set('port') with the value returned by server.address().port. This way the port param contains always the real port number, even when listen was called with port number 0.

Arguments
Name Type Description
[cb] Function

If specified, the callback is added as a listener for the server's "listening" event.

Returns
Name Type Description
result http.Server

A node http.Server with this application configured as the request handler.

app.model(Model, config)

Attach a model to the app. The Model will be available on the app.models object.

Example - Attach an existing model:

var User = loopback.User;
app.model(User);

Example - Attach an existing model, alter some aspects of the model:

var User = loopback.User;
app.model(User, { dataSource: 'db' });
Arguments
Name Type Description
Model Object or String

The model to attach.

config Object

The model's configuration.

config
Name Type Description
dataSource String or DataSource

The DataSource to which to attach the model.

[public] Boolean

Whether the model should be exposed via REST API.

[relations] Object

Relations to add/update.

Returns
Name Type Description
result ModelConstructor

the model class

app.models()

Get the models exported by the app. Returns only models defined using app.model()

There are two ways to access models:

  1. Call app.models() to get a list of all models.
var models = app.models();

models.forEach(function(Model) {
 console.log(Model.modelName); // color
});
  1. Use app.model to access a model by name. app.models has properties for all defined models.

The following example illustrates accessing the Product and CustomerReceipt models using the models object.

var loopback = require('loopback');
 var app = loopback();
 app.boot({
  dataSources: {
    db: {connector: 'memory'}
  }
});

app.model('product', {dataSource: 'db'});
app.model('customer-receipt', {dataSource: 'db'});

// available based on the given name
var Product = app.models.Product;

// also available as camelCase
var product = app.models.product;

// multi-word models are avaiable as pascal cased
var CustomerReceipt = app.models.CustomerReceipt;

// also available as camelCase
var customerReceipt = app.models.customerReceipt;
Returns
Name Type Description
result Array

Array of model classes.

app.remoteObjects()

Get all remote objects.

Returns
Name Type Description
result Object

Remote objects.

app.remotes()

Lazily load a set of remote objects.

NOTE: Calling app.remotes() more than once returns only a single set of remote objects.

Returns
Name Type Description
result RemoteObjects

app.middlewareFromConfig(factory, config)

Register a middleware using a factory function and a JSON config.

Example

app.middlewareFromConfig(compression, {
  enabled: true,
  phase: 'initial',
  params: {
    threshold: 128
  }
});
Arguments
Name Type Description
factory function

The factory function creating a middleware handler. Typically a result of require() call, e.g. require('compression').

config Object

The configuration.

config
Name Type Description
phase String

The phase to register the middleware in.

[enabled] Boolean

Whether the middleware is enabled. Default: true.

[params] Array

The arguments to pass to the factory function. Either an array of arguments, or the value of the first argument when the factory expects a single argument only.

[paths] Array or string or RegExp

Optional list of paths limiting the scope of the middleware.

Returns
Name Type Description
result object

this (fluent API)

app.defineMiddlewarePhases(nameOrArray)

Register (new) middleware phases.

If all names are new, then the phases are added just before "routes" phase. Otherwise the provided list of names is merged with the existing phases in such way that the order of phases is preserved.

Examples

// built-in phases:
// initial, session, auth, parse, routes, files, final

app.defineMiddlewarePhases('custom');
// new list of phases
// initial, session, auth, parse, custom, routes, files, final

app.defineMiddlewarePhases([
  'initial', 'postinit', 'preauth', 'routes', 'subapps'
]);
// new list of phases
// initial, postinit, preauth, session, auth, parse, custom,
// routes, subapps, files, final
Arguments
Name Type Description
nameOrArray string or Array.<string>

A phase name or a list of phase names to add.

Returns
Name Type Description
result object

this (fluent API)

app.middleware(name, handler)

Register a middleware handler to be executed in a given phase.

Arguments
Name Type Description
name string

The phase name, e.g. "init" or "routes".

[paths] Array or string or RegExp

Optional list of paths limiting the scope of the middleware. String paths are interpreted as expressjs path patterns, regular expressions are used as-is.

handler function

The middleware handler, one of function(req, res, next) or function(err, req, res, next)

Returns
Name Type Description
result object

this (fluent API)

loopback

loopback

LoopBack core module. It provides static properties and methods to create models and data sources. The module itself is a function that creates loopback app. For example:

var loopback = require('loopback');
var app = loopback();
Class Properties
Name Type Description
version String

Version of LoopBack framework. Static read-only property.

mime String
isBrowser Boolean

True if running in a browser environment; false otherwise. Static read-only property.

isServer Boolean

True if running in a server environment; false otherwise. Static read-only property.

registry Registry

The global Registry object.

faviconFile String

Path to a default favicon shipped with LoopBack. Use as follows: app.use(require('serve-favicon')(loopback.faviconFile));

Class: loopback Static Methods

loopback.autoAttach()

Attach any model that does not have a dataSource to the default dataSource for the type the Model requests

loopback.configureModel(ModelCtor, config)

Alter an existing Model class.

Arguments
Name Type Description
ModelCtor Model

The model constructor to alter.

config Object

Additional configuration to apply

config
Name Type Description
dataSource DataSource

Attach the model to a dataSource.

[relations] Object

Model relations to add/update.

loopback.createDataSource(name, options)

Create a data source with passing the provided options to the connector.

Arguments
Name Type Description
name String

Optional name.

options Object

Data Source options

options
Name Type Description
connector Object

LoopBack connector.

[*]

Other connector properties. See the relevant connector documentation.

loopback.createModel

Create a named vanilla JavaScript class constructor with an attached set of properties and options.

This function comes with two variants:

  • loopback.createModel(name, properties, options)
  • loopback.createModel(config)

In the second variant, the parameters name, properties and options are provided in the config object. Any additional config entries are interpreted as options, i.e. the following two configs are identical:

{ name: 'Customer', base: 'User' }
{ name: 'Customer', options: { base: 'User' } }

Example

Create an Author model using the three-parameter variant:

loopback.createModel(
  'Author',
  {
    firstName: 'string',
    lastName: 'string'
  },
  {
    relations: {
      books: {
        model: 'Book',
        type: 'hasAndBelongsToMany'
      }
    }
  }
);

Create the same model using a config object:

loopback.createModel({
  name: 'Author',
  properties: {
    firstName: 'string',
    lastName: 'string'
  },
  relations: {
    books: {
      model: 'Book',
      type: 'hasAndBelongsToMany'
    }
  }
});
Arguments
Name Type Description
name String

Unique name.

properties Object
options Object

(optional)

loopback.findModel(modelName)

Look up a model class by name from all models created by loopback.createModel()

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Model

The model class

loopback.getDefaultDataSourceForType(type)

Get the default dataSource for a given type.

Arguments
Name Type Description
type String

The datasource type.

Returns
Name Type Description
result DataSource

The data source instance

loopback.getModel(modelName)

Look up a model class by name from all models created by loopback.createModel(). Throw an error when no such model exists.

Arguments
Name Type Description
modelName String

The model name

Returns
Name Type Description
result Model

The model class

loopback.getModelByType(modelType)

Look up a model class by the base model class. The method can be used by LoopBack to find configured models in models.json over the base model.

Arguments
Name Type Description
modelType Model

The base model class

Returns
Name Type Description
result Model

The subclass if found or the base class

if()

Expose path to the default favicon file

only in node

loopback.memory([name])

Get an in-memory data source. Use one if it already exists.

Arguments
Name Type Description
[name] String

The name of the data source. If not provided, the 'default' is used.

loopback.remoteMethod(fn, options)

Add a remote method to a model.

Arguments
Name Type Description
fn Function
options Object

(optional)

loopback.setDefaultDataSourceForType(type, dataSource)

Set the default dataSource for a given type.

Arguments
Name Type Description
type String

The datasource type.

dataSource Object or DataSource

The data source settings or instance

Returns
Name Type Description
result DataSource

The data source instance.

loopback.template(path)

Create a template helper.

var render = loopback.template('foo.ejs');
var html = render({foo: 'bar'});
Arguments
Name Type Description
path String

Path to the template file.

Returns
Name Type Description
result Function

registry = new Registry()

Define and reference Models and DataSources.

Class: Registry Static Methods

addACL(acls, acl)

Add the acl entry to the acls

Arguments
Name Type Description
acls Array.<Object>
acl Object

Class: Registry Instance Methods

registry.autoAttach()

Attach any model that does not have a dataSource to the default dataSource for the type the Model requests

loopback.configureModel(ModelCtor, config)

Alter an existing Model class.

Arguments
Name Type Description
ModelCtor Model

The model constructor to alter.

config Object

Additional configuration to apply

config
Name Type Description
dataSource DataSource

Attach the model to a dataSource.

[relations] Object

Model relations to add/update.

registry.createDataSource(name, options)

Create a data source with passing the provided options to the connector.

Arguments
Name Type Description
name String

Optional name.

options Object

Data Source options

options
Name Type Description
connector Object

LoopBack connector.

[*]

Other connector properties. See the relevant connector documentation.

loopback.createModel

Create a named vanilla JavaScript class constructor with an attached set of properties and options.

This function comes with two variants:

  • loopback.createModel(name, properties, options)
  • loopback.createModel(config)

In the second variant, the parameters name, properties and options are provided in the config object. Any additional config entries are interpreted as options, i.e. the following two configs are identical:

{ name: 'Customer', base: 'User' }
{ name: 'Customer', options: { base: 'User' } }

Example

Create an Author model using the three-parameter variant:

loopback.createModel(
  'Author',
  {
    firstName: 'string',
    lastName: 'string'
  },
  {
    relations: {
      books: {
        model: 'Book',
        type: 'hasAndBelongsToMany'
      }
    }
  }
);

Create the same model using a config object:

loopback.createModel({
  name: 'Author',
  properties: {
    firstName: 'string',
    lastName: 'string'
  },
  relations: {
    books: {
      model: 'Book',
      type: 'hasAndBelongsToMany'
    }
  }
});
Arguments
Name Type Description
name String

Unique name.

properties Object
options Object

(optional)

loopback.findModel(modelName)

Look up a model class by name from all models created by loopback.createModel()

Arguments
Name Type Description
modelOrName String or Function

The model name or a Model constructor.

Returns
Name Type Description
result Model

The model class

registry.getDefaultDataSourceForType(type)

Get the default dataSource for a given type.

Arguments
Name Type Description
type String

The datasource type.

Returns
Name Type Description
result DataSource

The data source instance

loopback.getModel(modelName)

Look up a model class by name from all models created by loopback.createModel(). Throw an error when no such model exists.

Arguments
Name Type Description
modelOrName String

The model name or a Model constructor.

Returns
Name Type Description
result Model

The model class

loopback.getModelByType(modelType)

Look up a model class by the base model class. The method can be used by LoopBack to find configured models in models.json over the base model.

Arguments
Name Type Description
modelType Model

The base model class

Returns
Name Type Description
result Model

The subclass if found or the base class

registry.memory([name])

Get an in-memory data source. Use one if it already exists.

Arguments
Name Type Description
[name] String

The name of the data source. If not provided, the 'default' is used.

loopback.setDefaultDataSourceForType(type, dataSource)

Set the default dataSource for a given type.

Arguments
Name Type Description
type String

The datasource type.

dataSource Object or DataSource

The data source settings or instance

Returns
Name Type Description
result DataSource

The data source instance.

loopback.getCurrentContext()

Get the current context object. The context is preserved across async calls, it behaves like a thread-local storage.

Returns
Name Type Description
result ChainedContext

The context object or null.

loopback.runInContext(fn, context)

Run the given function in such way that loopback.getCurrentContext returns the provided context object.

NOTE

The method is supported on the server only, it does not work in the browser at the moment.

Arguments
Name Type Description
fn Function

The function to run, it will receive arguments (currentContext, currentDomain).

context ChainedContext

An optional context object. When no value is provided, then the default global context is used.

loopback.createContext(scopeName)

Create a new LoopBackContext instance that can be used for loopback.runInContext.

NOTES

At the moment, loopback.getCurrentContext supports a single global context instance only. If you call createContext() multiple times, getCurrentContext will return the last context created.

The method is supported on the server only, it does not work in the browser at the moment.

Arguments
Name Type Description
scopeName String

An optional scope name.

accessContext = new AccessContext(context)

Access context represents the context for a request to access protected resources

Arguments
Name Type Description
context Object

The context object

context
Name Type Description
principals Array.<Principal>

An array of principals

model Function

The model class

modelName String

The model name

modelId String

The model id

property String

The model property/method/relation name

method String

The model method to be invoked

accessType String

The access type

accessToken AccessToken

The access token

Returns
Name Type Description
result AccessContext

Class: AccessContext Instance Methods

accessContext.addPrincipal(principalType, principalId, [principalName])

Add a principal to the context

Arguments
Name Type Description
principalType String

The principal type

principalId

The principal id

[principalName] String

The principal name

Returns
Name Type Description
result boolean

accessContext.getAppId()

Get the application id

Returns
Name Type Description
result

accessContext.getUserId()

Get the user id

Returns
Name Type Description
result

accessContext.isAuthenticated()

Check if the access context has authenticated principals

Returns
Name Type Description
result boolean

accessRequest = new AccessRequest(model, property, accessType, permission)

A request to access protected resources.

Arguments
Name Type Description
model String

The model name

property String
accessType String

The access type

permission String

The requested permission

Returns
Name Type Description
result AccessRequest

Class: AccessRequest Instance Methods

accessRequest.exactlyMatches(acl)

Does the given ACL apply to this AccessRequest.

Arguments
Name Type Description
acl ACL

accessRequest.isAllowed()

Is the request for access allowed?

Returns
Name Type Description
result Boolean

accessRequest.isWildcard()

Does the request contain any wildcards?

Returns
Name Type Description
result Boolean

principal = new Principal(type, id, [name])

This class represents the abstract notion of a principal, which can be used to represent any entity, such as an individual, a corporation, and a login id

Arguments
Name Type Description
type String

The principal type

id

The princiapl id

[name] String

The principal name

Returns
Name Type Description
result Principal

Class: Principal Instance Methods

principal.equals(p)

Compare if two principals are equal Returns true if argument principal is equal to this principal.

Arguments
Name Type Description
p Object

The other principal

Base models

model = new Model(data)

The base class for all models.

Inheriting from Model

var properties = {...};
var options = {...};
var MyModel = loopback.Model.extend('MyModel', properties, options);

Options

  • trackChanges - If true, changes to the model will be tracked. Required for replication.

Events

Event: changed

Emitted after a model has been successfully created, saved, or updated. Argument: inst, model instance, object

MyModel.on('changed', function(inst) {
  console.log('model with id %s has been changed', inst.id);
  // => model with id 1 has been changed
});

Event: deleted

Emitted after an individual model has been deleted. Argument: id, model ID (number).

MyModel.on('deleted', function(id) {
  console.log('model with id %s has been deleted', id);
  // => model with id 1 has been deleted
});

Event: deletedAll

Emitted after an individual model has been deleted. Argument: where (optional), where filter, JSON object.

MyModel.on('deletedAll', function(where) {
  if (where) {
    console.log('all models where ', where, ' have been deleted');
    // => all models where
    // => {price: {gt: 100}}
    // => have been deleted
  }
});

Event: attached

Emitted after a Model has been attached to an app.

Event: dataSourceAttached

Emitted after a Model has been attached to a DataSource.

Event: set

Emitted when model property is set. Argument: inst, model instance, object

MyModel.on('set', function(inst) {
  console.log('model with id %s has been changed', inst.id);
  // => model with id 1 has been changed
});
Arguments
Name Type Description
data Object
Class Properties
Name Type Description
Model.modelName String

The name of the model. Static property.

Model.dataSource DataSource

Data source to which the model is connected, if any. Static property.

Model.sharedMethod SharedClass

The strong-remoting SharedClass that contains remoting (and http) metadata. Static property.

settings Object

Contains additional model settings.

settings.http.path string

Base URL of the model HTTP route.

[{string}]

settings.acls Array of ACLs for the model.

Class: Model Static Methods

Model.checkAccess(token, modelId, sharedMethod, ctx, callback)

Check if the given access token can invoke the specified method.

Arguments
Name Type Description
token AccessToken

The access token.

modelId

The model ID.

sharedMethod SharedMethod

The method in question.

ctx Object

The remote invocation context.

callback Function

The callback function.

Callback
Name Type Description
err String or Error

The error object.

allowed Boolean

True if the request is allowed; false otherwise.

Model.disableRemoteMethod(name, isStatic)

Disable remote invocation for the method with the given name.

Arguments
Name Type Description
name String

The name of the method.

isStatic Boolean

Is the method static (eg. MyModel.myMethod)? Pass false if the method defined on the prototype (eg. MyModel.prototype.myMethod).

Model.getApp(callback)

Get the Application object to which the Model is attached.

Arguments
Name Type Description
callback Function

Callback function called with (err, app) arguments.

Callback
Name Type Description
err Error

Error object; see Error object.

app Application

Attached application object.

Model.nestRemoting(relationName, [options], pathName, filterMethod, paramName, getterName, hooks, filterCallback)

Enabled deeply-nested queries of related models via REST API.

Arguments
Name Type Description
relationName String

Name of the nested relation.

[options] Object

It is optional. See below.

pathName String

The HTTP path (relative to the model) at which your remote method is exposed.

filterMethod String

The filter name.

paramName String

The argument name that the remote method accepts.

getterName String

The getter name.

hooks Boolean

Whether to inherit before/after hooks.

filterCallback Function

The Optional filter function.

Callback
Name Type Description
SharedMethod Object

object. See here.

RelationDefinition Object

object which includes relation type, ModelConstructor of modelFrom, modelTo, keyFrom, keyTo and more relation definitions.

Model.remoteMethod(name, options)

Enable remote invocation for the specified method. See Remote methods for more information.

Static method example:

Model.myMethod();
Model.remoteMethod('myMethod');
Arguments
Name Type Description
name String

The name of the method.

options Object

The remoting options. See Remote methods - Options.

Model.setup()

The loopback.Model.extend() method calls this when you create a model that extends another model. Add any setup or configuration code you want executed when the model is created. See Setting up a custom model.

persistedModel = new PersistedModel

PersistedModel

Extends Model with basic query and CRUD support.

Change Event

Listen for model changes using the change event.

MyPersistedModel.on('changed', function(obj) {
   console.log(obj) // => the changed model
});

Class: PersistedModel Static Methods

PersistedModel.bulkUpdate(updates, callback)

Apply an update list.

Note: this is not atomic

Arguments
Name Type Description
updates Array

An updates list, usually from createUpdates().

callback Function

Callback function.

PersistedModel.changes(since, filter, callback)

Get the changes to a model since the specified checkpoint. Provide a filter object to reduce the number of results returned.

Arguments
Name Type Description
since Number

Return only changes since this checkpoint.

filter Object

Include only changes that match this filter, the same as for #persistedmodel-find).

callback Function

Callback function called with (err, changes) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

changes Array

An array of Change objects.

PersistedModel.checkpoint(callback)

Create a checkpoint.

Arguments
Name Type Description
callback Function

PersistedModel.count([where], callback)

Return the number of records that match the optional "where" filter.

Arguments
Name Type Description
[where] Object

Optional where filter, like { key: val, key2: {gt: 'val2'}, ...}
See Where filter.

callback Function

Callback function called with (err, count) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

count Number

Number of instances updated.

PersistedModel.create({Object}|[{Object}], callback)

Create new instance of Model, and save to database.

Arguments
Name Type Description
{Object}|[{Object}]

data Optional data argument. Can be either a single model instance or an array of instances.

callback Function

Callback function called with cb(err, obj) signature.

Callback
Name Type Description
err Error

Error object; see Error object.

models Object

Model instances or null.

PersistedModel.createChangeStream(options, callback)

Create a change stream. See here for more info

Arguments
Name Type Description
options Object
options.where Object

Only changes to models matching this where filter will be included in the ChangeStream.

callback Function
Callback
Name Type Description
err Error
changes ChangeStream

PersistedModel.createUpdates(deltas, callback)

Create an update list (for Model.bulkUpdate()) from a delta list (result of Change.diff()).

Arguments
Name Type Description
deltas Array
callback Function

PersistedModel.currentCheckpoint(callback)

Get the current checkpoint ID.

Arguments
Name Type Description
callback Function

Callback function called with (err, currentCheckpointId) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

currentCheckpointId Number

Current checkpoint ID.

PersistedModel.destroyAll([where], callback)

Destroy all model instances that match the optional where specification.

Arguments
Name Type Description
[where] Object

Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...}
See Where filter.

callback Function

Optional callback function called with (err, info) arguments.

Callback
Name Type Description
err Error

Error object; see Error object.

info Object

Additional information about the command outcome.

info.count Number

Number of instances (rows, documents) destroyed.

PersistedModel.destroyById(id, callback)

Destroy model instance with the specified ID.

Arguments
Name Type Description
id

The ID value of model instance to delete.

callback Function

Callback function called with (err) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

PersistedModel.diff(since, remoteChanges, callback)

Get a set of deltas and conflicts since the given checkpoint.

See Change.diff() for details.

Arguments
Name Type Description
since Number

Find deltas since this checkpoint.

remoteChanges Array

An array of change objects.

callback Function

Callback function called with (err, result) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

result Object

Object with deltas and conflicts properties; see Change.diff() for details.

PersistedModel.enableChangeTracking()

Enable the tracking of changes made to the model. Usually for replication.

PersistedModel.exists(id, callback)

Check whether a model instance exists in database.

Arguments
Name Type Description
id id

Identifier of object (primary key value).

callback Function

Callback function called with (err, exists) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

exists Boolean

True if the instance with the specified ID exists; false otherwise.

PersistedModel.find([filter], callback)

Find all model instances that match filter specification. See Querying models.

Arguments
Name Type Description
[filter] Object

Optional Filter JSON object; see below.

callback Function

Callback function called with (err, returned-instances) arguments. Required.

[filter]
Name Type Description
fields String or Object or Array

Identify fields to include in return result.
See Fields filter.

include String or Object or Array

See PersistedModel.include documentation.
See Include filter.

limit Number

Maximum number of instances to return.
See Limit filter.

order String

Sort order: either "ASC" for ascending or "DESC" for descending.
See Order filter.

skip Number

Number of results to skip.
See Skip filter.

where Object

Where clause, like { where: { key: val, key2: {gt: 'val2'}, ...} }
See Where filter.

Callback
Name Type Description
err Error

Error object; see Error object.

models Array

Model instances matching the filter, or null if none found.

PersistedModel.findById(id, [filter], callback)

Find object by ID with an optional filter for include/fields.

Arguments
Name Type Description
id

Primary key value

[filter] Object

Optional Filter JSON object; see below.

callback Function

Callback function called with (err, instance) arguments. Required.

[filter]
Name Type Description
fields String or Object or Array

Identify fields to include in return result.
See Fields filter.

include String or Object or Array

See PersistedModel.include documentation.
See Include filter.

Callback
Name Type Description
err Error

Error object; see Error object.

instance Object

Model instance matching the specified ID or null if no instance matches.

PersistedModel.findOne([filter], callback)

Find one model instance that matches filter specification. Same as find, but limited to one result; Returns object, not collection.

Arguments
Name Type Description
[filter] Object

Optional Filter JSON object; see below.

callback Function

Callback function called with (err, returned-instance) arguments. Required.

[filter]
Name Type Description
fields String or Object or Array

Identify fields to include in return result.
See Fields filter.

include String or Object or Array

See PersistedModel.include documentation.
See Include filter.

order String

Sort order: either "ASC" for ascending or "DESC" for descending.
See Order filter.

skip Number

Number of results to skip.
See Skip filter.

where Object

Where clause, like {where: { key: val, key2: {gt: 'val2'}, ...} }
See Where filter.

Callback
Name Type Description
err Error

Error object; see Error object.

model Array

First model instance that matches the filter or null if none found.

PersistedModel.findOrCreate([filter], data, callback)

Finds one record matching the optional filter object. If not found, creates the object using the data provided as second argument. In this sense it is the same as find, but limited to one object. Returns an object, not collection. If you don't provide the filter object argument, it tries to locate an existing object that matches the data argument.

Arguments
Name Type Description
[filter] Object

Optional Filter object; see below.

data Object

Data to insert if object matching the where filter is not found.

callback Function

Callback function called with cb(err, instance, created) arguments. Required.

[filter]
Name Type Description
fields String or Object or Array

Identify fields to include in return result.
See Fields filter.

include String or Object or Array

See PersistedModel.include documentation.
See Include filter.

limit Number

Maximum number of instances to return.
See Limit filter.

order String

Sort order: either "ASC" for ascending or "DESC" for descending.
See Order filter.

skip Number

Number of results to skip.
See Skip filter.

where Object

Where clause, like {where: {key: val, key2: {gt: val2}, ...}}
See Where filter.

Callback
Name Type Description
err Error

Error object; see Error object.

instance Object

Model instance matching the where filter, if found.

created Boolean

True if the instance matching the where filter was created.

PersistedModel.getChangeModel()

Get the Change model. Throws an error if the change model is not correctly setup.

PersistedModel.getIdName()

Get the id property name of the constructor.

Returns
Name Type Description
result String

The id property name

PersistedModel.getSourceId(callback)

Get the source identifier for this model or dataSource.

Arguments
Name Type Description
callback Function

Callback function called with (err, id) arguments.

Callback
Name Type Description
err Error

Error object; see Error object.

sourceId String

Source identifier for the model or dataSource.

PersistedModel.handleChangeError(err)

Handle a change error. Override this method in a subclassing model to customize change error handling.

Arguments
Name Type Description
err Error

Error object; see Error object.

PersistedModel.rectifyChange(id, callback)

Specify that a change to the model with the given ID has occurred.

Arguments
Name Type Description
id

The ID of the model that has changed.

callback Function
Callback
Name Type Description
err Error

PersistedModel.replicate([since], targetModel, [options], [callback])

Replicate changes since the given checkpoint to the given target model.

Arguments
Name Type Description
[since] Number

Since this checkpoint

targetModel Model

Target this model class

[options] Object
[options.filter] Object

Replicate models that match this filter

[callback] Function

Callback function called with (err, conflicts) arguments.

Callback
Name Type Description
err Error

Error object; see Error object.

conflicts Array.<Conflict>

A list of changes that could not be replicated due to conflicts.

{Object] checkpoints The new checkpoints to use as the "since"

argument for the next replication.

PersistedModel.updateAll([where], data, callback)

Update multiple instances that match the where clause.

Example:

Employee.updateAll({managerId: 'x001'}, {managerId: 'x002'}, function(err, info) {
    ...
});
Arguments
Name Type Description
[where] Object

Optional where filter, like { key: val, key2: {gt: 'val2'}, ...}
see Where filter.

data Object

Object containing data to replace matching instances, if any.

callback Function

Callback function called with (err, info) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

info Object

Additional information about the command outcome.

info.count Number

Number of instances (rows, documents) updated.

PersistedModel.upsert(data, callback)

Update or insert a model instance

Arguments
Name Type Description
data Object

The model instance data to insert.

callback Function

Callback function called with cb(err, obj) signature.

Callback
Name Type Description
err Error

Error object; see Error object.

model Object

Updated model instance.

Class: PersistedModel Instance Methods

persistedModel.destroy(callback)

Deletes the model from persistence. Triggers destroy hook (async) before and after destroying object.

Arguments
Name Type Description
callback Function

Callback function.

persistedModel.getId()

Get the id value for the PersistedModel.

Returns
Name Type Description
result

The id value

persistedModel.getIdName()

Get the id property name of the constructor.

Returns
Name Type Description
result String

The id property name

persistedModel.isNewRecord()

Determine if the data model is new.

Returns
Name Type Description
result Boolean

Returns true if the data model is new; false otherwise.

persistedModel.reload(callback)

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

Arguments
Name Type Description
callback Function

Callback function called with (err, instance) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

instance Object

Model instance.

persistedModel.save([options], callback)

Save model instance. If the instance doesn't have an ID, then calls create instead. Triggers: validate, save, update, or create.

Arguments
Name Type Description
[options] Object

See below.

callback Function

Optional callback function called with (err, obj) arguments.

[options]
Name Type Description
validate Boolean

Perform validation before saving. Default is true.

throws Boolean

If true, throw a validation error; WARNING: This can crash Node. If false, report the error via callback. Default is false.

Callback
Name Type Description
err Error

Error object; see Error object.

instance Object

Model instance saved or created.

persistedModel.setId(val)

Set the correct id property for the PersistedModel. Uses the setId method if the model is attached to connector that defines it. Otherwise, uses the default lookup. Override this method to handle complex IDs.

Arguments
Name Type Description
val

The id value. Will be converted to the type that the id property specifies.

persistedModel.updateAttribute(name, value, callback)

Update a single attribute. Equivalent 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) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

instance Object

Updated instance.

persistedModel.updateAttributes(data, callback)

Update set of attributes. Performs validation before updating.

Triggers: validation, save and update hooks

Arguments
Name Type Description
data Object

Data to update.

callback Function

Callback function called with (err, instance) arguments. Required.

Callback
Name Type Description
err Error

Error object; see Error object.

instance Object

Updated instance.

Middleware

loopback.context([options])

Context middleware.

var app = loopback();
app.use(loopback.context(options);
app.use(loopback.rest());
app.listen();
Arguments
Name Type Description
[options] Object

Options for context

[options]
Name Type Description
name String

Context scope name.

enableHttpContext Boolean

Whether HTTP context is enabled. Default is false.

loopback.favicon()

Serve the LoopBack favicon.

loopback.rest()

Expose models over REST.

For example:

app.use(loopback.rest());

For more information, see Exposing models over a REST API.

loopback.static(root, [options])

Serve static assets of a LoopBack application.

Arguments
Name Type Description
root string

The root directory from which the static assets are to be served.

options object

Refer to express documentation for the full list of available options.

loopback.status()

Return HTTP response with basic application status information: date the application was started and uptime, in JSON format. For example:

{
 "started": "2014-06-05T00:26:49.750Z",
 "uptime": 9.394
}

rewriteUserLiteral()

Rewrite the url to replace current user literal with the logged in user id

loopback.token([options])

Check for an access token in cookies, headers, and query string parameters. This function always checks for the following:

  • access_token (params only)
  • X-Access-Token (headers only)
  • authorization (headers and cookies)

It checks for these values in cookies, headers, and query string parameters in addition to the items specified in the options parameter.

NOTE: This function only checks for signed cookies.

The following example illustrates how to check for an accessToken in a custom cookie, query string parameter and header called foo-auth.

app.use(loopback.token({
  cookies: ['foo-auth'],
  headers: ['foo-auth', 'X-Foo-Auth'],
  params: ['foo-auth', 'foo_auth']
}));
Arguments
Name Type Description
[options] Object

Each option array is used to add additional keys to find an accessToken for a request.

[options]
Name Type Description
[cookies] Array

Array of cookie names.

[headers] Array

Array of header names.

[params] Array

Array of param names.

[searchDefaultTokenKeys] Boolean

Use the default search locations for Token in request

[enableDoublecheck] Boolean

Execute middleware although an instance mounted earlier in the chain didn't find a token

[overwriteExistingToken] Boolean

only has effect in combination with enableDoublecheck. If truthy, will allow to overwrite an existing accessToken.

[model] Function or String

AccessToken model name or class to use.

[currentUserLiteral] String

String literal for the current user.

loopback.urlNotFound()

Convert any request not handled so far to a 404 error to be handled by error-handling middleware.

Built-in models

accessToken = new AccessToken

AccessToken

Token based authentication and access control.

Default ACLs

  • DENY EVERYONE *
  • ALLOW EVERYONE create
Class Properties
Name Type Description
id String

Generated token ID.

ttl Number

Time to live in seconds, 2 weeks by default.

created Date

When the token was created.

settings Object

Extends the Model.settings object.

settings.accessTokenIdLength Number

Length of the base64-encoded string access token. Default value is 64. Increase the length for a more secure access token.

Class: AccessToken Static Methods

AccessToken.createAccessTokenId(callback)

Create a cryptographically random access token id.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
token String

AccessToken.findForRequest(req, [options], callback)

Find a token for the given ServerRequest.

Arguments
Name Type Description
req ServerRequest
[options] Object

Options for finding the token

callback Function
Callback
Name Type Description
err Error
token AccessToken

Class: AccessToken Instance Methods

accessToken.validate(callback)

Validate the token.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
isValid Boolean

ACL

ACL

A Model for access control meta data.

System grants permissions to principals (users/applications, can be grouped into roles).

Protected resource: the model data and operations (model/property/method/relation/…)

For a given principal, such as client application and/or user, is it allowed to access (read/write/execute) the protected resource?

Class Properties
Name Type Description
model String

Name of the model.

property String

Name of the property, method, scope, or relation.

accessType String

Type of access being granted: one of READ, WRITE, or EXECUTE.

permission String

Type of permission granted. One of:

  • ALARM: Generate an alarm, in a system-dependent way, the access specified in the permissions component of the ACL entry.
  • ALLOW: Explicitly grants access to the resource.
  • AUDIT: Log, in a system-dependent way, the access specified in the permissions component of the ACL entry.
  • DENY: Explicitly denies access to the resource.
principalType String

Type of the principal; one of: Application, Use, Role.

principalId String

ID of the principal - such as appId, userId or roleId.

settings Object

Extends the Model.settings object.

settings.defaultPermission String

Default permission setting: ALLOW, DENY, ALARM, or AUDIT. Default is ALLOW. Set to DENY to prohibit all API access by default.

Class: ACL Static Methods

ACL.checkAccessForContext(context, callback)

Check if the request has the permission to access.

Arguments
Name Type Description
context Object

See below.

callback Function

Callback function

context
Name Type Description
principals Array.<Object>

An array of principals.

model String or Model

The model name or model class.

id

The model instance ID.

property String

The property/method/relation name.

accessType String

The access type: READ, REPLICATE, WRITE, or EXECUTE.

ACL.checkAccessForToken(token, model, modelId, method, callback)

Check if the given access token can invoke the method

Arguments
Name Type Description
token AccessToken

The access token

model String

The model name

modelId

The model id

method String

The method name

callback Function

Callback function

Callback
Name Type Description
err String or Error

The error object

allowed Boolean

is the request allowed

ACL.checkPermission(principalType, principalId, model, property, accessType, callback)

Check if the given principal is allowed to access the model/property

Arguments
Name Type Description
principalType String

The principal type.

principalId String

The principal ID.

model String

The model name.

property String

The property/method/relation name.

accessType String

The access type.

callback Function

Callback function.

Callback
Name Type Description
err String or Error

The error object

result AccessRequest

The access permission

ACL.getMatchingScore(rule, req)

Calculate the matching score for the given rule and request

Arguments
Name Type Description
rule ACL

The ACL entry

req AccessRequest

The request

Returns
Name Type Description
result Number

ACL.isMappedToRole(principalType, principalId, role, cb)

Check if the given principal is mapped to the role

Arguments
Name Type Description
principalType String

Principal type

principalId String

Principal id/name

role String

Role id/name

cb Function

Callback function

ACL.resolvePrincipal(type, id, cb)

Resolve a principal by type/id

Arguments
Name Type Description
type String

Principal type - ROLE/APP/USER

id String or Number

Principal id or name

cb Function

Callback function

Class: ACL Instance Methods

aCL.score(req)

Get matching score for the given AccessRequest.

Arguments
Name Type Description
req AccessRequest

The request

Returns
Name Type Description
result Number

score

application = new Application

Application

Manage client applications and organize their users.

Class Properties
Name Type Description
id String

Generated ID.

name String

Name; required.

description String

Text description

icon String

String Icon image URL.

owner String

User ID of the developer who registers the application.

email String

E-mail address

emailVerified Boolean

Whether the e-mail is verified.

url String

OAuth 2.0 application URL.

{String}[]

callbackUrls The OAuth 2.0 code/token callback URL.

status String

Status of the application; Either production, sandbox (default), or disabled.

created Date

Date Application object was created. Default: current date.

modified Date

Date Application object was modified. Default: current date.

pushSettings.apns Object

APNS configuration, see the options below and also https://github.com/argon/node-apn/blob/master/doc/apn.markdown

pushSettings.apns.production Boolean

Whether to use production Apple Push Notification Service (APNS) servers to send push notifications. If true, uses gateway.push.apple.com:2195 and feedback.push.apple.com:2196. If false, uses gateway.sandbox.push.apple.com:2195 and feedback.sandbox.push.apple.com:2196

pushSettings.apns.certData String

The certificate data loaded from the cert.pem file (APNS).

pushSettings.apns.keyData String

The key data loaded from the key.pem file (APNS).

pushSettings.apns.pushOptions.gateway String

(APNS).

pushSettings.apns.pushOptions.port Number

(APNS).

pushSettings.apns.feedbackOptions.gateway String

(APNS).

pushSettings.apns.feedbackOptions.port Number

(APNS).

pushSettings.apns.feedbackOptions.batchFeedback Boolean

(APNS).

pushSettings.apns.feedbackOptions.interval Number

(APNS).

pushSettings.gcm.serverApiKey: String

Google Cloud Messaging API key.

authenticationEnabled Boolean
anonymousAllowed Boolean
authenticationSchemes Array

List of authentication schemes (see below).

authenticationSchemes.scheme String

Scheme name. Supported values: local, facebook, google, twitter, linkedin, github.

authenticationSchemes.credential Object

Scheme-specific credentials.

Class: Application Static Methods

Application.authenticate(appId, key, callback)

Authenticate the application id and key.

Arguments
Name Type Description
appId Any
key String
callback Function
Callback
Name Type Description
err Error
matched String

The matching key; one of: - clientKey

  • javaScriptKey
  • restApiKey
  • windowsKey
  • masterKey

Application.register(owner, name, options, callback)

Register a new application

Arguments
Name Type Description
owner String

Owner's user ID.

name String

Name of the application

options Object

Other options

callback Function

Callback function

Application.resetKeys(appId, callback)

Reset keys for a given application by the appId

Arguments
Name Type Description
appId Any
callback Function
Callback
Name Type Description
err Error

Class: Application Instance Methods

application.resetKeys(callback)

Reset keys for the application instance

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error

change = new Change

Change

Change list entry.

Class Properties
Name Type Description
id String

Hash of the modelName and ID.

rev String

The current model revision.

prev String

The previous model revision.

checkpoint Number

The current checkpoint at time of the change.

modelName String

Model name.

modelId String

Model ID.

settings Object

Extends the Model.settings object.

settings.hashAlgorithm String

Algorithm used to create cryptographic hash, used as argument to crypto.createHash. Default is sha1.

settings.ignoreErrors Boolean

By default, when changes are rectified, an error will throw an exception. However, if this setting is true, then errors will not throw exceptions.

Class: Change Static Methods

Change.bothDeleted(a, b)

Are both changes deletes?

Arguments
Name Type Description
a Change
b Change

Change.diff(modelName, since, remoteChanges, callback)

Determine the differences for a given model since a given checkpoint.

The callback will contain an error or result.

result

{
  deltas: Array,
  conflicts: Array
}

deltas

An array of changes that differ from remoteChanges.

conflicts

An array of changes that conflict with remoteChanges.

Arguments
Name Type Description
modelName String
since Number

Compare changes after this checkpoint

remoteChanges Array.<Change>

A set of changes to compare

callback Function
Callback
Name Type Description
err Error
result Object

See above.

Change.findOrCreateChange(modelName, modelId, callback)

Find or create a change for the given model.

Arguments
Name Type Description
modelName String
modelId String
callback Function
Callback
Name Type Description
err Error
change Change

Change.getCheckpointModel()

Get the checkpoint model.

Change.hash(str)

Create a hash of the given string with the options.hashAlgorithm. Default: sha1

Arguments
Name Type Description
str String

The string to be hashed

Change.idForModel(modelName, modelId)

Get an identifier for a given model.

Arguments
Name Type Description
modelName String
modelId String

Change.rectifyAll(cb)

Correct all change list entries.

Arguments
Name Type Description
cb Function

Change.rectifyModelChanges(modelName, modelIds, callback)

Track the recent change of the given modelIds.

Arguments
Name Type Description
modelName String
modelIds Array
callback Function
Callback
Name Type Description
err Error
changes Array

Changes that were tracked

Change.revisionForInst(inst)

Get the revision string for the given object

Arguments
Name Type Description
inst Object

The data to get the revision string for

Class: Change Instance Methods

change.conflictsWith(change)

Does this change conflict with the given change.

Arguments
Name Type Description
change Change

change.currentRevision(callback)

Get a change's current revision based on current data.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
rev String

The current revision

change.equals(change)

Compare two changes.

Arguments
Name Type Description
change Change

change.getModelCtor()

Get the Model class for change.modelName.

change.isBasedOn(change)

Determine if the change is based on the given change.

Arguments
Name Type Description
change Change

change.rectify(callback)

Update (or create) the change with the current revision.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
change Change

change.type()

Get a change's type. Returns one of:

  • Change.UPDATE
  • Change.CREATE
  • Change.DELETE
  • Change.UNKNOWN

change.Conflict = new Change.Conflict

Change.Conflict

When two changes conflict a conflict is created.

Note: call conflict.fetch() to get the target and source models.

Arguments
Name Type Description
modelId
SourceModel PersistedModel
TargetModel PersistedModel
Class Properties
Name Type Description
source ModelClass

The source model instance

target ModelClass

The target model instance

Class: Change.Conflict Instance Methods

conflict.changes(callback)

Get the conflicting changes.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
sourceChange Change
targetChange Change

conflict.models(callback)

Fetch the conflicting models.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
source PersistedModel
target PersistedModel

conflict.resolve(callback)

Resolve the conflict.

Set the source change's previous revision to the current revision of the (conflicting) target change. Since the changes are no longer conflicting and appear as if the source change was based on the target, they will be replicated normally as part of the next replicate() call.

This is effectively resolving the conflict using the source version.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error

conflict.resolveManually(data, callback)

Resolve the conflict using the supplied instance data.

Arguments
Name Type Description
data Object

The set of changes to apply on the model instance. Use null value to delete the source instance instead.

callback Function
Callback
Name Type Description
err Error

conflict.resolveUsingSource(callback)

Resolve the conflict using the instance data in the source model.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error

conflict.resolveUsingTarget(callback)

Resolve the conflict using the instance data in the target model.

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error

conflict.swapParties()

Return a new Conflict instance with swapped Source and Target models.

This is useful when resolving a conflict in one-way replication, where the source data must not be changed:

conflict.swapParties().resolveUsingTarget(cb);
Returns
Name Type Description
result Conflict

A new Conflict instance.

conflict.type(callback)

Determine the conflict type.

Possible results are

  • Change.UPDATE: Source and target models were updated.
  • Change.DELETE: Source and or target model was deleted.
  • Change.UNKNOWN: the conflict type is uknown or due to an error.
Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
type String

The conflict type.

email = new Email

Email

Email model. Extends LoopBack base Model.

Class Properties
Name Type Description
to String

Email addressee. Required.

from String

Email sender address. Required.

subject String

Email subject string. Required.

text String

Text body of email.

html String

HTML body of email.

Class: Email Static Methods

Email.send(options, callback)

Send an email with the given options.

Example Options:

{
  from: "Fred Foo <foo@blurdybloop.com>", // sender address
  to: "bar@blurdybloop.com, baz@blurdybloop.com", // list of receivers
  subject: "Hello", // Subject line
  text: "Hello world", // plaintext body
  html: "<b>Hello world</b>" // html body
}

See https://github.com/andris9/Nodemailer for other supported options.

Arguments
Name Type Description
options Object

See below

callback Function

Called after the e-mail is sent or the sending failed

options
Name Type Description
from String

Senders's email address

to String

List of one or more recipient email addresses (comma-delimited)

subject String

Subject line

text String

Body text

html String

Body HTML (optional)

Class: Email Instance Methods

email.send()

A shortcut for Email.send(this).

Role object

Role

The Role model

Class: Role Static Methods

Role.getRoles(context, callback)

List roles for a given principal.

Arguments
Name Type Description
context Object

The security context.

callback Function

Callback function.

Callback
Name Type Description
err Error

Error object.

roles Array.<String>

An array of role IDs

Role.isAuthenticated(context, callback)

Check if the user ID is authenticated

Arguments
Name Type Description
context Object

The security context.

callback Function

Callback function.

Callback
Name Type Description
err Error

Error object.

isAuthenticated Boolean

True if the user is authenticated.

Role.isInRole(role, context, callback)

Check if a given principal is in the specified role.

Arguments
Name Type Description
role String

The role name.

context Object

The context object.

callback Function

Callback function.

Callback
Name Type Description
err Error

Error object.

isInRole Boolean

True if the principal is in the specified role.

Role.isOwner(modelClass, modelId, userId, callback)

Check if a given user ID is the owner the model instance.

Arguments
Name Type Description
modelClass Function

The model class

modelId

The model ID

userId

The user ID

callback Function

Callback function

Role.registerResolver(role, resolver)

Add custom handler for roles.

Arguments
Name Type Description
role String

Name of role.

resolver Function

Function that determines if a principal is in the specified role. Should provide a callback or return a promise.

roleMapping = new RoleMapping

RoleMapping

The RoleMapping model extends from the built in loopback.Model type.

Class Properties
Name Type Description
id String

Generated ID.

name String

Name of the role.

Description String

Text description.

Class: RoleMapping Instance Methods

roleMapping.application(callback)

Get the application principal

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
application Application

roleMapping.childRole(callback)

Get the child role principal

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
childUser User

roleMapping.user(callback)

Get the user principal

Arguments
Name Type Description
callback Function
Callback
Name Type Description
err Error
user User

scope = new Scope

Scope

Resource owner grants/delegates permissions to client applications

For a protected resource, does the client application have the authorization from the resource owner (user or system)?

Scope has many resource access entries

Class: Scope Static Methods

Scope.checkPermission(scope, model, property, accessType, callback)

Check if the given scope is allowed to access the model/property

Arguments
Name Type Description
scope String

The scope name

model String

The model name

property String

The property/method/relation name

accessType String

The access type

callback Function
Callback
Name Type Description
err String or Error

The error object

result AccessRequest

The access permission

user = new User

User

Built-in User model. Extends LoopBack PersistedModel.

Default User ACLs.

  • DENY EVERYONE *
  • ALLOW EVERYONE create
  • ALLOW OWNER deleteById
  • ALLOW EVERYONE login
  • ALLOW EVERYONE logout
  • ALLOW OWNER findById
  • ALLOW OWNER updateAttributes
Class Properties
Name Type Description
username String

Must be unique.

password String

Hidden from remote clients.

email String

Must be valid email.

emailVerified Boolean

Set when a user's email has been verified via confirm().

verificationToken String

Set when verify() is called.

realm String

The namespace the user belongs to. See Partitioning users with realms for details.

created Date

The property is not used by LoopBack, you are free to use it for your own purposes.

lastUpdated Date

The property is not used by LoopBack, you are free to use it for your own purposes.

status String

The property is not used by LoopBack, you are free to use it for your own purposes.

settings Object

Extends the Model.settings object.

settings.emailVerificationRequired Boolean

Require the email verification process before allowing a login.

settings.ttl Number

Default time to live (in seconds) for the AccessToken created by User.login() / user.createAccessToken(). Default is 1209600 (2 weeks)

settings.maxTTL Number

The max value a user can request a token to be alive / valid for. Default is 31556926 (1 year)

settings.realmRequired Boolean

Require a realm when logging in a user.

settings.realmDelimiter String

When set a realm is required.

settings.resetPasswordTokenTTL Number

Time to live for password reset AccessToken. Default is 900 (15 minutes).

settings.saltWorkFactor Number

The bcrypt salt work factor. Default is 10.

settings.caseSensitiveEmail Boolean

Enable case sensitive email.

Class: User Static Methods

User.confirm(userId, token, redirect, callback)

Confirm the user's identity.

Arguments
Name Type Description
userId Any
token String

The validation token

redirect String

URL to redirect the user to once confirmed

callback Function
Callback
Name Type Description
err Error

User.generateVerificationToken(user, cb)

A default verification token generator which accepts the user the token is being generated for and a callback function to indicate completion. This one uses the crypto library and 64 random bytes (converted to hex) for the token. When used in combination with the user.verify() method this function will be called with the user object as it's context (this).

Arguments
Name Type Description
user object

The User this token is being generated for.

cb Function

The generator must pass back the new token with this function call

User.login(credentials, [include], callback)

Login a user by with the given credentials.

   User.login({username: 'foo', password: 'bar'}, function (err, token) {
     console.log(token.id);
   });
Arguments
Name Type Description
credentials Object

username/password or email/password

[include] Array.<String> or String

Optionally set it to "user" to include the user info

callback Function

Callback function

Callback
Name Type Description
err Error

Error object

token AccessToken

Access token if login is successful

User.logout(accessTokenID, callback)

Logout a user with the given accessToken id.

   User.logout('asd0a9f8dsj9s0s3223mk', function (err) {
     console.log(err || 'Logged out');
   });
Arguments
Name Type Description
accessTokenID String
callback Function
Callback
Name Type Description
err Error

User.normalizeCredentials(credentials, realmRequired, realmDelimiter)

Normalize the credentials

Arguments
Name Type Description
credentials Object

The credential object

realmRequired Boolean
realmDelimiter String

The realm delimiter, if not set, no realm is needed

Returns
Name Type Description
result Object

The normalized credential object

User.resetPassword(options, callback)

Create a short lived acess token for temporary login. Allows users to change passwords if forgotten.

Arguments
Name Type Description
options Object
callback Function
options
Name Type Description
email String

The user's email address

Callback
Name Type Description
err Error

Class: User Instance Methods

user.createAccessToken(ttl, [options], cb)

Create access token for the logged in user. This method can be overridden to customize how access tokens are generated

Arguments
Name Type Description
ttl Number

The requested ttl

[options] Object

The options for access token, such as scope, appId

cb Function

The callback function

Callback
Name Type Description
err String or Error

The error string or object

token AccessToken

The generated access token object

user.hasPassword(password)

Compare the given password with the users hashed password.

Arguments
Name Type Description
password String

The plain text password

Returns
Name Type Description
result Boolean

user.verify(options)

Verify a user's identity by sending them a confirmation email.

   var options = {
     type: 'email',
     to: user.email,
     template: 'verify.ejs',
     redirect: '/',
     tokenGenerator: function (user, cb) { cb("random-token"); }
   };

   user.verify(options, next);
Arguments
Name Type Description
options Object
options
Name Type Description
type String

Must be 'email'.

to String

Email address to which verification email is sent.

from String

Sender email addresss, for example 'noreply@myapp.com'.

subject String

Subject line text.

text String

Text of email.

template String

Name of template that displays verification page, for example, `'verify.ejs'.

redirect String

Page to which user will be redirected after they verify their email, for example '/' for root URI.

generateVerificationToken Function

A function to be used to generate the verification token. It must accept the user object and a callback function. This function should NOT add the token to the user object, instead simply execute the callback with the token! User saving and email sending will be handled in the verify() method.