Define a model class
Name | Type | Description |
---|---|---|
className |
String
|
|
properties |
Object
|
hash of class properties in format |
settings |
Object
|
other configuration of class |
more advanced case 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 }
});
Register a property for the model class
Name | Type | Description |
---|---|---|
propertyName |
|
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
Name | Type | Description |
---|---|---|
model |
String
|
name of model |
props |
Object
|
hash of properties Example:
|
Get the schema name
Resolve the type string to be a function, for example, 'String' to String
Name | Type | Description |
---|---|---|
type |
String
|
The type string, such as 'number', 'Number', 'boolean', or 'String'. It's case insensitive |
Name | Type | Description |
---|---|---|
result |
Function
|
if the type is resolved |
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 |
Introspect the json document to build a corresponding model
Name | Type | Description |
---|---|---|
name |
String
|
The model name |
json |
Object
|
The json object |
[Object} options The options |
|
Name | Type | Description |
---|---|---|
result |
|
{} |
Export public API
Name | Type | Description |
---|---|---|
models |
Object
|
Model constructors |
Name | Type | Description |
---|---|---|
definitions |
Object
|
Definitions of the models |
Determine the spherical distance between two geo points.
Determine the spherical distance to the given point.
Simple serialization.
Export the GeoPoint
class.
Model class - base class for all persist objects
provides common API to access any database connector.
This class describes only abstract behavior layer, refer to lib/connectors/*.js
to learn more about specific connector implementations
ModelBaseClass
mixes Validatable
and Hookable
classes methods
Name | Type | Description |
---|---|---|
data |
Object
|
initial object data |
Name | Type | Description |
---|---|---|
prop |
String
|
property name |
params |
Object
|
various property configuration |
Return string representation of class
Convert instance to Object
Name | Type | Description |
---|---|---|
onlySchema |
Boolean
|
restrict properties to dataSource only, default false when onlySchema == true, only properties defined in dataSource returned, otherwise all enumerable properties returned |
Name | Type | Description |
---|---|---|
result |
Object
|
|
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 operation it just reset object to it's initial state
Module exports class Model
DataSource - connector-specific classes factory.
All classes in single dataSource shares same connector type and one database connection
Name | Type | Description |
---|---|---|
name |
String
|
type of dataSource connector (mysql, mongoose, oracle, redis) |
settings |
Object
|
any database-specific settings which we need to establish connection (of course it depends on specific connector)
|
DataSource creation, waiting for connection callback var dataSource = new DataSource('mysql', { database: 'myapp_test' });
dataSource.define(...);
dataSource.on('connected', function () {
// work with database
});
Define a model class
Name | Type | Description |
---|---|---|
className |
String
|
|
properties |
Object
|
hash of class properties in format |
settings |
Object
|
other configuration of class |
more advanced case var User = dataSource.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 }
});
Mixin DataAccessObject methods.
Name | Type | Description |
---|---|---|
ModelCtor |
Function
|
The model constructor |
Attach an existing model to a data source.
Name | Type | Description |
---|---|---|
modelClass |
Function
|
The model constructor |
Define single property named prop
on model
Name | Type | Description |
---|---|---|
model |
String
|
name of model |
prop |
String
|
name of property |
params |
Object
|
property settings |
Drop each model table and re-create. This method make sense only for sql connectors.
Name | Type | Description |
---|---|---|
or |
String
|
{[String]} Models to be migrated, if not present, apply to all models |
[cb] |
Function
|
The callback function |
Update existing database tables. This method make sense only for sql connectors.
Name | Type | Description |
---|---|---|
or |
String
|
{[String]} Models to be migrated, if not present, apply to all models |
[cb] |
Function
|
The callback function |
Discover existing database tables. This method returns an array of model objects, including {type, name, onwer}
options
all: true - Discovering all models, false - Discovering the models owned by the current user
views: true - Including views, false - only tables
limit: The page size
offset: The starting index
Name | Type | Description |
---|---|---|
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
The synchronous version of discoverModelDefinitions
Name | Type | Description |
---|---|---|
options |
Object
|
The options |
Name | Type | Description |
---|---|---|
result |
|
Discover properties for a given model.
property description
owner {String} The database owner or schema
tableName {String} The table/view name
columnName {String} The column name
dataType {String} The data type
dataLength {Number} The data length
dataPrecision {Number} The numeric data precision
dataScale {Number} The numeric data scale
nullable {Boolean} If the data can be null
options
owner/schema The database owner/schema
Name | Type | Description |
---|---|---|
modelName |
String
|
The table/view name |
options |
Object
|
The options |
[cb] |
Function
|
The callback function |
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:
owner {String} => table schema (may be null)
tableName {String} => table name
columnName {String} => column name
keySeq {Number} => sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2 would represent the second column within the primary key).
pkName {String} => primary key name (may be null)
The owner, default to current user
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 discoverPrimaryKeys
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 |
|
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 one schema from the given model without following the relations
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 |
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 |
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 |
Freeze dataSource. Behavior depends on connector
Return table name for specified modelName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
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 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 names for specified modelName
Name | Type | Description |
---|---|---|
modelName |
String
|
The model name |
Name | Type | Description |
---|---|---|
result |
Array.<String>
|
column names |
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 |
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 |
Close database connection
Name | Type | Description |
---|---|---|
[cb] |
Fucntion
|
The callback function |
Enable a data source operation to be remote.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Disable a data source operation to be remote.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Get an operation's metadata.
Name | Type | Description |
---|---|---|
operation |
String
|
The operation name |
Get all operations.
Define an operation to the data source
Name | Type | Description |
---|---|---|
name |
String
|
The operation name |
options |
Object
|
The options |
[Function} fn The function |
|
Check if the backend is a relational DB
Name | Type | Description |
---|---|---|
result |
Boolean
|
Check if the data source is ready
Name | Type | Description |
---|---|---|
obj |
|
|
args |
|
Name | Type | Description |
---|---|---|
result |
boolean
|
Define a hidden property
Name | Type | Description |
---|---|---|
obj |
Object
|
The property owner |
key |
String
|
The property name |
value |
Mixed
|
The default value |
Define readonly property on object
Name | Type | Description |
---|---|---|
obj |
Object
|
The property owner |
key |
String
|
The property name |
value |
Mixed
|
The default value |
Export public API
DAO class - base class for all persist objects
provides common API to access any database connector.
This class describes only abstract behavior layer, refer to lib/connectors/*.js
to learn more about specific connector implementations
DataAccessObject
mixes Inclusion
classes methods
Name | Type | Description |
---|---|---|
data |
Object
|
initial object data |
Create new instance of Model class, saved in database
Name | Type | Description |
---|---|---|
data |
|
[optional] |
callback(err, |
|
obj) callback called with arguments:
|
Update or insert a model instance
Name | Type | Description |
---|---|---|
data |
Object
|
The model instance data |
[callback] |
Function
|
The callback function |
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) |
Check whether a model instance exists in database
Name | Type | Description |
---|---|---|
id |
id
|
identifier of object (primary key value) |
cb |
Function
|
callbacl called with (err, exists: Bool) |
Find object by id
Name | Type | Description |
---|---|---|
id |
|
primary key value |
cb |
Function
|
callback called with (err, instance) |
Find all instances of Model, matched by query
make sure you have marked as index: true
fields for filter or sort
Name | Type | Description |
---|---|---|
params |
Object
|
(optional)
|
callback |
Function
|
(required) called with arguments:
|
Find one record, same as all
, limited by 1 and return object, not collection
Name | Type | Description |
---|---|---|
params |
Object
|
search conditions: {where: {test: 'me'}} |
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) |
Destroy a record by id
Name | Type | Description |
---|---|---|
id |
|
The id value |
cb |
Function
|
callback called with (err) |
Return count of matched records
Name | Type | Description |
---|---|---|
where |
Object
|
search conditions (optional) |
cb |
Function
|
callback, called with (err, count) |
Save instance. When instance haven't id, create method called instead. Triggers: validate, save, update | create
Name | Type | Description |
---|---|---|
options |
|
{validate: true, throws: false} [optional] |
callback(err, |
|
obj) |
Update single attribute
equals to `updateAttributes({name: value}, cb)
Name | Type | Description |
---|---|---|
name |
String
|
name of property |
value |
Mixed
|
value of property |
callback |
Function
|
callback called with (err, instance) |
Update set of attributes
this method performs validation before updating
Name | Type | Description |
---|---|---|
data |
Object
|
data to update |
callback |
Function
|
callback called with (err, instance) |
Reload object from persistence
Name | Type | Description |
---|---|---|
callback |
Function
|
called with (err, instance) arguments |
Define readonly property on object
Name | Type | Description |
---|---|---|
obj |
Object
|
|
key |
String
|
|
value |
Mixed
|
Define scope
Module exports class Model
Delete object from persistence
Hooks mixins
Module exports
List of hooks available
Allows you to load relations of several objects and optimize numbers of requests.
Name | Type | Description |
---|---|---|
objects |
Array
|
array of instances |
{String}, |
|
{Object} or {Array} include - which relations you want to load. |
cb |
Function
|
Callback called when relations are loaded Examples:
|
Include mixin for ./model.js
Declare hasMany relation
Name | Type | Description |
---|---|---|
anotherClass |
Relation
|
class to has many |
params |
Object
|
configuration {as:, foreignKey:} |
User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
Declare belongsTo relation
Name | Type | Description |
---|---|---|
anotherClass |
Class
|
class to belong |
params |
Object
|
configuration {as: 'propertyName', foreignKey: 'keyName'} Usage examples Suppose model Post have a belongsTo relationship with User (the author of the post). You could declare it this way: Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); When a post is loaded, you can load the related author with: post.author(function(err, user) { // the user variable is your user object }); The related object is cached, so if later you try to get again the author, no additional request will be made. But there is an optional boolean parameter in first position that set whether or not you want to reload the cache: post.author(true, function(err, user) { // The user is reloaded, even if it was already cached. }); This optional parameter default value is false, so the related object will be loaded from cache if available. |
Many-to-many relation
Post.hasAndBelongsToMany('tags'); creates connection model 'PostTag'
Presence validator
Length validator
Numericality validator
Inclusion validator
Exclusion validator
Format validator
Custom validator
Uniqueness validator
This method performs validation, triggers validation hooks.
Before validation obj.errors
collection cleaned.
Each validation can add errors to obj.errors
collection.
If collection is not blank, validation failed.
Name | Type | Description |
---|---|---|
callback |
Function
|
called with (valid) |
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');
});
Return true when v is undefined, blank array, null or empty string otherwise returns false
Name | Type | Description |
---|---|---|
v |
Mix
|
Name | Type | Description |
---|---|---|
result |
Boolean
|
whether |
Module exports
Validation mixins for model.js
Basically validation configurators is just class methods, which adds validations
configs to AbstractClass._validations. Each of this validations run when
obj.isValid()
method called.
Each configurator can accept n params (n-1 field names and one config). Config
is {Object} depends on specific validation, but all of them has one common part:
message
member. It can be just string, when only one situation possible,
e.g. Post.validatesPresenceOf('title', { message: 'can not be blank' });
In more complicated cases it can be {Hash} of messages (for each case):
User.validatesLengthOf('password', { min: 6, max: 20, message: {min: 'too short', max: 'too long'}});
Validate presence. This validation fails when validated field is blank.
Default error message "can't be blank"
with custom message Post.validatesPresenceOf('title', {message: 'Can not be blank'});
Validate length. Three kinds of validations: min, max, is.
Default error messages:
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'}});
Validate numericality.
User.validatesNumericalityOf('age', { message: { number: '...' }});
User.validatesNumericalityOf('age', {int: true, message: { int: '...' }});
Default error messages:
Validate inclusion in set
User.validatesInclusionOf('gender', {in: ['male', 'female']});
User.validatesInclusionOf('role', {
in: ['admin', 'moderator', 'user'], message: 'is not allowed'
});
Default error message: is not included in the list
Validate exclusion
Company.validatesExclusionOf('domain', {in: ['www', 'admin']});
Default error message: is reserved
Validate format
Default error message: is invalid
Validate using custom validator
Default error message: is invalid
Example:
User.validate('name', customValidator, {message: 'Bad name'});
function customValidator(err) {
if (this.name === 'bad') err();
});
var user = new User({name: 'Peter'});
user.isValid(); // true
user.name = 'bad';
user.isValid(); // false
Validate using custom async validator
Default error message: is invalid
Example:
User.validateAsync('name', customValidator, {message: 'Bad name'});
function customValidator(err, done) {
process.nextTick(function () {
if (this.name === 'bad') err();
done();
});
});
var user = new User({name: 'Peter'});
user.isValid(); // false (because async validation setup)
user.isValid(function (isValid) {
isValid; // true
})
user.name = 'bad';
user.isValid(); // false
user.isValid(function (isValid) {
isValid; // false
})
Validate uniqueness
Default error message: is not unique