For example, the following creates a DataSource, and waits for a connection callback. var dataSource = new DataSource('mysql', { database: 'myapp_test' });
dataSource.define(...);
dataSource.on('connected', function () {
// work with database
});
Name | Type | Description |
---|---|---|
name |
String
|
Type of dataSource connector (mysql, mongoose, oracle, redis) |
settings |
Object
|
Database-specific settings to establish connection (settings depend on specific connector). See above. |
Define readonly property on object
Name | Type | Description |
---|---|---|
obj |
Object
|
The property owner |
key |
String
|
The property name |
value |
Mixed
|
The default value |
Define a hidden property
Name | Type | Description |
---|---|---|
obj |
Object
|
The property owner |
key |
String
|
The property name |
value |
Mixed
|
The default value |
Attach an existing model to a data source.
Name | Type | Description |
---|---|---|
modelClass |
Function
|
The model constructor |
Drop each model table and re-create. This method applies only to SQL connectors.
Name | Type | Description |
---|---|---|
model |
String
|
Model to migrate. If not present, apply to all models. Can also be an array of Strings. |
cb |
Function
|
Callback function. Optional. WARNING: Calling this function will cause all data to be lost! Use autoupdate if you need to preserve data. |
Update existing database tables. This method make sense only for sql connectors.
Name | Type | Description |
---|---|---|
model |
String
|
Model to migrate. If not present, apply to all models. Can also be an array of Strings. |
[cb] |
Function
|
The callback function |
Return column metadata for specified modelName and propertyName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
propertyName |
|
The property name |
Name | Type | Description |
---|---|---|
result |
Object
|
column metadata |
Return column name for specified modelName and propertyName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
propertyName |
|
The property name |
Name | Type | Description |
---|---|---|
result |
String
|
columnName |
Return column names for specified modelName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
column names |
Define a model class. Simple example:
var User = dataSource.createModel('User', {
email: String,
password: String,
birthDate: Date,
activated: Boolean
});
More advanced example
var User = dataSource.createModel('User', {
email: { type: String, limit: 150, index: true },
password: { type: String, limit: 50 },
birthDate: Date,
registrationDate: {type: Date, default: function () { return new Date }},
activated: { type: Boolean, default: false }
});
You can also define an ACL when you create a new data source with the DataSource.create()
method. For example:
var Customer = ds.createModel('Customer', {
name: {
type: String,
acls: [
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.WRITE, permission: ACL.DENY},
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
]
}
}, {
acls: [
{principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
]
});
Name | Type | Description |
---|---|---|
className |
String
|
Name of the model to create. |
properties |
Object
|
Hash of class properties in format |
settings |
Object
|
Other configuration settings. |
Name | Type | Description |
---|---|---|
result |
|
newly created class |
Define foreign key to another model
Name | Type | Description |
---|---|---|
className |
String
|
The model name that owns the key |
key |
String
|
Name of key field |
foreignClassName |
String
|
The foreign model name |
Define an operation to the data source
Name | Type | Description |
---|---|---|
name |
String
|
The operation name |
options |
Object
|
The options |
fn |
Function
|
The function |
Define single property named prop
on model
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
prop |
String
|
Name of property |
params |
Object
|
Property settings |
Disable remote access to a data source operation. Each connector has its own set of set enabled
and disabled operations. To list the operations, call dataSource.operations()
.
var oracle = loopback.createDataSource({
connector: require('loopback-connector-oracle'),
host: '...',
...
});
oracle.disableRemote('destroyAll');
Notes:
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Close database connection
Name | Type | Description |
---|---|---|
cb |
Fucntion
|
The callback function. Optional. |
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
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
The options |
[cb] |
Function
|
The callback function |
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
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
The options |
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
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
The synchronous version of discoverExportedForeignKeys
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover foreign keys for a given owner/modelName
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
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
The synchronous version of discoverForeignKeys
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover existing database tables. This method returns an array of model objects, including {type, name, onwer}
Name | Type | Description |
---|---|---|
options |
Object
|
The options |
Callback |
Function
|
function. Optional. |
options |
Object
|
Discovery options. Keys in options object: |
Name | Type | Description |
---|---|---|
all |
|
{Boolean} If true, discover all models; if false, discover only models owned by the current user. |
views |
|
{Boolean} If true, nclude views; if false, only tables. |
limit |
|
{Number} Page size |
offset |
|
{Number} Starting index |
The synchronous version of discoverModelDefinitions
Name | Type | Description |
---|---|---|
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
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:
Name | Type | Description |
---|---|---|
modelName |
String
|
The table/view name |
options |
Object
|
The options |
cb |
Function
|
Callback function. Optional |
The synchronous version of discoverModelProperties
Name | Type | Description |
---|---|---|
modelName |
String
|
The table/view name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover primary keys for a given owner/modelName.
Each primary key column description has the following columns:
The owner defaults to current user.
Options:
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
The synchronous version of discoverPrimaryKeys
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover one schema from the given model without following the relations. Example schema from oracle connector:*
{
"name": "Product",
"options": {
"idInjection": false,
"oracle": {
"schema": "BLACKPOOL",
"table": "PRODUCT"
}
},
"properties": {
"id": {
"type": "String",
"required": true,
"length": 20,
"id": 1,
"oracle": {
"columnName": "ID",
"dataType": "VARCHAR2",
"dataLength": 20,
"nullable": "N"
}
},
"name": {
"type": "String",
"required": false,
"length": 64,
"oracle": {
"columnName": "NAME",
"dataType": "VARCHAR2",
"dataLength": 64,
"nullable": "Y"
}
},
...
"fireModes": {
"type": "String",
"required": false,
"length": 64,
"oracle": {
"columnName": "FIRE_MODES",
"dataType": "VARCHAR2",
"dataLength": 64,
"nullable": "Y"
}
}
}
}
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
The options |
[cb] |
Function
|
The callback function |
Discover schema from a given modelName/view
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
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
The options |
[cb] |
Function
|
The callback function |
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
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
[options] |
Object
|
The options |
Enable remote access to a data source operation. Each connector has its own set of set
remotely enabled and disabled operations. To list the operations, call dataSource.operations()
.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Freeze dataSource. Behavior depends on connector
See ModelBuilder.getModel
See ModelBuilder.getModelDefinition
Get an operation's metadata.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Get the data source types
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
The data source type, such as ['db', 'nosql', 'mongodb'], ['rest'], or ['db', 'rdbms', 'mysql'] |
Find the ID column name
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
String
|
columnName for ID |
Find the ID property name
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
String
|
property name for ID |
Find the ID property names sorted by the index
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
property names for IDs |
Find the id property definition
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Object
|
The id property definition |
Check whether migrations needed This method make sense only for sql connectors.
Name | Type | Description |
---|---|---|
[models] |
Array.<String>
|
A model name or an array of model names. If not present, apply to all models |
Check if the backend is a relational DB
Name | Type | Description |
---|---|---|
result |
Boolean
|
Mixin DataAccessObject methods.
Name | Type | Description |
---|---|---|
ModelCtor |
Function
|
The model constructor |
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
},
...
}
Check if the data source is ready. Returns a Boolean value.
Name | Type | Description |
---|---|---|
obj |
|
{Object} ? |
args |
|
{Object} ? |
Check the data source supports the specified types.
Name | Type | Description |
---|---|---|
types |
String
|
Type name or an array of type names. Can also be array of Strings. |
Name | Type | Description |
---|---|---|
result |
Boolean
|
true if all types are supported by the data source |
Return table name for specified modelName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
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, ...]
});
Name | Type | Description |
---|---|---|
latlong |
Object
|
Object with two Number properties: lat and long. |
Name | Type | Description |
---|---|---|
lat |
Number
|
|
lng |
Number
|
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
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. |
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
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). |
Simple serialization.
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.
Name | Type | Description |
---|---|---|
data |
Object
|
Initial object data |
Return count of matched records
Name | Type | Description |
---|---|---|
where |
Object
|
Search conditions (optional) |
cb |
Function
|
Callback, called with (err, count) |
Create new instance of Model class, saved in database. The callback function is called with arguments:
Name | Type | Description |
---|---|---|
data |
|
{Object} Optional data object |
callback |
|
{Function} Callback function |
Check whether a model instance exists in database
Name | Type | Description |
---|---|---|
id |
id
|
Identifier of object (primary key value) |
cb |
Function
|
Callback function called with (err, exists: Bool) |
Find all instances of Model, matched by query
make sure you have marked as index: true
fields for filter or sort
Name | Type | Description |
---|---|---|
[query] |
Object
|
the query object
|
callback |
Function
|
(required) called with two arguments: err (null or Error), array of instances |
Find object by id
Name | Type | Description |
---|---|---|
id |
|
Primary key value |
cb |
Function
|
Callback called with (err, instance) |
Find one record, same as all
, limited by 1 and return object, not collection
Name | Type | Description |
---|---|---|
query |
Object
|
search conditions: {where: {test: 'me'}} |
cb |
Function
|
callback called with (err, instance) |
Find one record, same as all
, limited by 1 and return object, not collection,
if not found, create using data provided as second argument
Name | Type | Description |
---|---|---|
query |
Object
|
Search conditions: {where: {test: 'me'}}. |
data |
Object
|
Object to create. |
cb |
Function
|
Callback called with (err, instance) |
Destroy all matching records
Name | Type | Description |
---|---|---|
[where] |
Object
|
An object that defines the criteria |
[cb] |
Function
|
Callback called with (err) |
Delete the record with the specified ID.
Aliases are destroyById
and deleteById
.
Name | Type | Description |
---|---|---|
id |
|
The id value |
cb |
Function
|
Callback called with (err) |
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.
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 |
Update or insert a model instance.
updateOrCreate
is an alias
Name | Type | Description |
---|---|---|
data |
Object
|
The model instance data |
callback |
Function
|
The callback function (optional). |
Reload object from persistence
Requires id
member of object
to be able to call find
Name | Type | Description |
---|---|---|
callback |
Function
|
Called with (err, instance) arguments |
Save instance. If the instance does not have an ID, call create
instead.
Triggers: validate, save, update or create.
Name | Type | Description |
---|---|---|
options |
Object
|
Optional options to use. |
callback |
Function
|
Callback function with err and object arguments |
Name | Type | Description |
---|---|---|
validate |
Boolean
|
Default is true. |
throws |
Boolean
|
Default is false. |
Update a single attribute.
Equivalent to updateAttributes({name: value}, cb)
Name | Type | Description |
---|---|---|
name |
String
|
Name of property |
value |
Mixed
|
Value of property |
callback |
Function
|
Callback function called with (err, instance) |
Update saet of attributes. Performs validation before updating.
Name | Type | Description |
---|---|---|
data |
Object
|
Data to update |
callback |
Function
|
Callback function called with (err, instance) |
Model class: base class for all persistent objects.
ModelBaseClass
mixes Validatable
and Hookable
classes methods
Name | Type | Description |
---|---|---|
data |
Object
|
Initial object data |
Define a property on the model.
Name | Type | Description |
---|---|---|
prop |
String
|
Property name |
params |
Object
|
Various property configuration |
Return string representation of class
This overrides the default toString()
method
Checks is property changed based on current property and initial value
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name |
Reset dirty attributes. This method does not perform any database operations; it just resets the object to its initial state.
Convert model instance to a plain JSON object. Returns a canonical object representation (no getters and setters).
Name | Type | Description |
---|---|---|
onlySchema |
Boolean
|
Restrict properties to dataSource only. Default is false. If true, the function returns only properties defined in the schema; Otherwise it returns all enumerable properties. |
ModelBuilder - A builder to define data models.
Register a property for the model class
Name | Type | Description |
---|---|---|
propertyName |
String
|
Name of the property. |
Introspect the JSON document to build a corresponding model.
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
json |
Object
|
The JSON object |
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
{} |
Build models from schema definitions
schemas
can be one of the following:
Name | Type | Description |
---|---|---|
schemas |
|
The schemas |
Name | Type | Description |
---|---|---|
result |
Object
|
A map of model constructors keyed by model name |
Define a model class. Simple example:
var User = modelBuilder.define('User', {
email: String,
password: String,
birthDate: Date,
activated: Boolean
});
More advanced example:
var User = modelBuilder.define('User', {
email: { type: String, limit: 150, index: true },
password: { type: String, limit: 50 },
birthDate: Date,
registrationDate: {type: Date, default: function () { return new Date }},
activated: { type: Boolean, default: false }
});
Name | Type | Description |
---|---|---|
className |
String
|
Name of class |
properties |
Object
|
Hash of class properties in format |
settings |
Object
|
Other configuration of class |
Define single property named propertyName
on model
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
propertyName |
String
|
Name of property |
propertyDefinition |
Object
|
Property settings |
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 }
});
Name | Type | Description |
---|---|---|
model |
String
|
Name of model |
props |
Object
|
Hash of properties |
Get a model by name.
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
forceCreate |
Boolean
|
Whether the create a stub for the given name if a model doesn't exist. Returns {*} The model class |
Get the model definition by name
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
ModelDefinition
|
The model definition |
Get the schema name
Resolve the type string to be a function, for example, 'String' to String. Returns {Function} if the type is resolved
Name | Type | Description |
---|---|---|
type |
String
|
The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive |
Inclusion - Model mixin.
Enables you to load relations of several objects and optimize numbers of requests.
Examples:
Load all users' posts with only one additional request:
User.include(users, 'posts', function() {});
Or
User.include(users, ['posts'], function() {});
Load all users posts and passports with two additional requests:
User.include(users, ['posts', 'passports'], function() {});
Load all passports owner (users), and all posts of each owner loaded:
Passport.include(passports, {owner: 'posts'}, function() {});
Passport.include(passports, {owner: ['posts', 'passports']});
``` Passport.include(passports, {owner: [{posts: 'images'}, 'passports']});
Name | Type | Description |
---|---|---|
objects |
Array
|
Array of instances |
{String}, |
|
{Object} or {Array} include Which relations to load. |
cb |
Function
|
Callback called when relations are loaded |
Relations class. Use to define relationships between models.
Add the target model instance to the 'hasMany' relation
Name | Type | Description |
---|---|---|
{Object|ID) acInst The actual instance or id value |
|
Declare "belongsTo" relation that sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.
For example, if an application includes users and posts, and each post can be written by exactly one user.
The following code specifies that Post
has a reference called author
to the User
model via the userId
property of Post
as the foreign key.
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
You can then access the author in one of the following styles. Get the User object for the post author asynchronously:
post.author(callback);
Get the User object for the post author synchronously:
post.author();
Set the author to be the given user:
post.author(user)
Examples:
Suppose the model Post has a *belongsTo* relationship with User (the author of the post). You could declare it this way:
```js
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
When a post is loaded, you can load the related author with:
post.author(function(err, user) {
// the user variable is your user object
});
The related object is cached, so if later you try to get again the author, no additional request will be made. But there is an optional boolean parameter in first position that set whether or not you want to reload the cache:
post.author(true, function(err, user) {
// The user is reloaded, even if it was already cached.
});
This optional parameter default value is false, so the related object will be loaded from cache if available.
Name | Type | Description |
---|---|---|
anotherClass |
Class
|
Class to belong |
Parameters |
Object
|
Configuration parameters |
Name | Type | Description |
---|---|---|
as |
String
|
Can be 'propertyName' |
foreignKey |
String
|
Name of foreign key property. |
A hasAndBelongsToMany relation creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes users and groups, with each group having many users and each user appearing in many groups, you could declare the models this way:
User.hasAndBelongsToMany('groups', {model: Group, foreignKey: 'groupId'});
Then, to get the groups to which the user belongs:
user.groups(callback);
Create a new group and connect it with the user:
user.groups.create(data, callback);
Connect an existing group with the user:
user.groups.add(group, callback);
Remove the user from the group:
user.groups.remove(group, callback);
Name | Type | Description |
---|---|---|
anotherClass |
String or Function
|
target class to hasAndBelongsToMany or name of the relation |
params |
Object
|
configuration {as: String, foreignKey: *, model: ModelClass} |
Name | Type | Description |
---|---|---|
model |
Object
|
Model name |
foreignKey |
String
|
Property name of foreign key field. |
Define a "one to many" relationship by specifying the model name
Examples:
User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
Book.hasMany(Chapter);
Or, equivalently:
Book.hasMany('chapters', {model: Chapter});
Name | Type | Description |
---|---|---|
anotherClass |
Relation
|
Class to has many |
parameters |
Object
|
Configuration parameters |
Name | Type | Description |
---|---|---|
as |
String
|
|
foreignKey |
String
|
Property name of foreign key field. |
model |
Object
|
Model object |
Find the relation by foreign key
Name | Type | Description |
---|---|---|
foreignKey |
|
The foreign key |
Name | Type | Description |
---|---|---|
result |
Object
|
The relation object |
Remove the target model instance from the 'hasMany' relation
Name | Type | Description |
---|---|---|
{Object|ID) acInst The actual instance or id value |
|
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 have a
message
member property. It can be just string, when only one situation possible,
For example: 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'}});
Validate exclusion. Require a property value not be in the specified array.
Example: Company.validatesExclusionOf('domain', {in: ['www', 'admin']});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
Name | Type | Description |
---|---|---|
in |
Array
|
Array Property must match one of the values in the array to be valid. |
message |
String
|
Optional error message if property is not valid. Default error message: "is reserved". |
Validate format. Require a model to include a property that matches the given format.
Require a model to include a property that matches the given format. Example:
User.validatesFormat('name', {with: /\w+/});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
Name | Type | Description |
---|---|---|
with |
RegExp
|
Regular expression to validate format. |
message |
String
|
Optional error message if property is not valid. Default error message: " is invalid". |
Validate inclusion in set. Require a value for property to be in the specified array.
Example:
User.validatesInclusionOf('gender', {in: ['male', 'female']});
User.validatesInclusionOf('role', {
in: ['admin', 'moderator', 'user'], message: 'is not allowed'
});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
Name | Type | Description |
---|---|---|
in |
Array
|
Array Property must match one of the values in the array to be valid. |
message |
String
|
Optional error message if property is not valid. Default error message: "is not included in the list". |
Validate length. Require a property length to be within a specified range. Three kinds of validations: min, max, is.
Default error messages:
Example: length validations
User.validatesLengthOf('password', {min: 7});
User.validatesLengthOf('email', {max: 100});
User.validatesLengthOf('state', {is: 2});
User.validatesLengthOf('nick', {min: 3, max: 15});
Example: length validations with custom error messages
User.validatesLengthOf('password', {min: 7, message: {min: 'too weak'}});
User.validatesLengthOf('state', {is: 2, message: {is: 'is not valid state name'}});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
Name | Type | Description |
---|---|---|
is |
Number
|
Value that property must equal to validate. |
min |
Number
|
Value that property must be less than to be valid. |
max |
Number
|
Value that property must be less than to be valid. |
message |
Object
|
Optional Object with string properties for custom error message for each validation: is, min, or max |
Validate numericality. Requires a value for property to be either an integer or number.
Example
User.validatesNumericalityOf('age', { message: { number: '...' }});
User.validatesNumericalityOf('age', {int: true, message: { int: '...' }});
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
Name | Type | Description |
---|---|---|
int |
Boolean
|
If true, then property must be an integer to be valid. |
message |
Object
|
Optional object with string properties for 'int' for integer validation. Default error messages: - number: is not a number
|
Validate presence of one or more specified properties. Requires a model to include a property to be considered valid; fails when validated field is blank.
For example, validate presence of title
Post.validatesPresenceOf('title');
Validate that model has first, last, and age properties:
User.validatesPresenceOf('first', 'last', 'age');
Example with custom message
Post.validatesPresenceOf('title', {message: 'Cannot be blank'});
Name | Type | Description |
---|---|---|
propertyName |
String
|
One or more property names. |
errMsg |
Object
|
Optional custom error message. Default is "can't be blank" |
Name | Type | Description |
---|---|---|
message |
String
|
Error message to use instead of default. |
Validate uniqueness. Ensure the value for property is unique in the collection of models. Not available for all connectors. Currently supported with these connectors:
// The login must be unique across all User instances.
User.validatesUniquenessOf('login');
// Assuming SiteUser.belongsTo(Site)
// The login must be unique within each Site.
SiteUser.validateUniquenessOf('login', { scopedTo: ['siteId'] });
Name | Type | Description |
---|---|---|
propertyName |
String
|
Property name to validate. |
Options |
Object
|
Name | Type | Description |
---|---|---|
with |
RegExp
|
Regular expression to validate format. |
scopedTo |
Array.<String>
|
List of properties defining the scope. |
message |
String
|
Optional error message if property is not valid. Default error message: "is not unique". |
ValidationError is raised when the application attempts to save an invalid model instance. Example:
{
"name": "ValidationError",
"status": 422,
"message": "The Model instance is not valid. \
See `details` property of the error object for more info.",
"statusCode": 422,
"details": {
"context": "user",
"codes": {
"password": [
"presence"
],
"email": [
"uniqueness"
]
},
"messages": {
"password": [
"can't be blank"
],
"email": [
"Email already exists"
]
}
},
}
You might run into situations where you need to raise a validation error yourself, for example in a "before" hook or a custom model method.
MyModel.prototype.preflight = function(changes, callback) {
// Update properties, do not save to db
for (var key in changes) {
model[key] = changes[key];
}
if (model.isValid()) {
return callback(null, { success: true });
}
// This line shows how to create a ValidationError
err = new ValidationError(model);
callback(err);
}
This method performs validation and triggers validation hooks.
Before validation the obj.errors
collection is cleaned.
Each validation can add errors to obj.errors
collection.
If collection is not blank, validation failed.
NOTE: This method can be called as synchronous only when no asynchronous validation is configured. It's strongly recommended to run all validations as asyncronous.
Example: ExpressJS controller: render user if valid, show flash otherwise
user.isValid(function (valid) {
if (valid) res.render({user: user});
else res.flash('error', 'User is not valid'), console.log(user.errors), res.redirect('/users');
});
Another example:
user.isValid(function (valid) {
if (!valid) {
console.log(user.errors);
// => hash of errors
// => {
// => username: [errmessage, errmessage, ...],
// => email: ...
// => }
}
});
Name | Type | Description |
---|---|---|
callback |
Function
|
called with (valid) |
Name | Type | Description |
---|---|---|
result |
Boolean
|
True if no asynchronouse validation is configured and all properties pass validation. |