Subscribe to our list to receive the latest updates on Node on Fire

Class: Model

Model

new Model()

Do not construct a Model instance yourself, instead, you can construct a model via App#model.

The model is a collection of properties and associations. Through a model you can find, update, create and delete (CRUD) model instances.

Methods

authorize(authenticateMap)

Authorizes the current authenticator, for example, your user model. To declare an authenticator have a look at PropertyTypes#Authenticate.

For example, consider the following authenticator model:

function User() {
    this.email = [this.String, this.Authenticate];
    this.fullName = [this.String];
}
app.model(User);

In your controller, you can sign in the user via the following:

function SignInController($scope, UserModel) {
    $scope.signIn = function(email, password) {
        return UserModel.authorize({email: email, password: password})
            .then(function(user) {
                // The user signed in. TODO: redirect the user to the signed-in area: $location.path('/dashboard')
            })
            .catch(function(error) {
                // TODO: Show the user some error.
            });
    };
}
app.controller(SignInController);

To sign out a user you can use Model#signOut. To return the currently signed in user, have a look at Model#getMe.

Parameters:
Name Type Description
authenticateMap Dictionary

Dictionary containing the authenticating property and the password.

count(propertyName, whereMap)

Counts the number of model instances.

Parameters:
Name Type Description
propertyName String

The property to count. Optional.

whereMap Dictionary

The where map. Optional. See Model#find.

Returns:

Integer.

Type
Promise

create(createMap)

Creates one or more model instance. This method is isomorphic and available on the back-end and the front-end.

For example, to create one model instance in the back-end:

app.controller('/sign-in', function AuthController($scope, UserModel) {
    $scope.createUser = function(userMap) {
        return UserModel.create(userMap);
    };
});

You can also create multiple model instances when passing an array. When creating multiple model instances, they are created one-by-one in the database and no bulk-insert is performed. This is an improvement for a future release.

Parameters:
Name Type Description
createMap Dictionary

A dictionary to create one model instance, or an array to create multiple model instances.

Returns:

Either resolves with a model instance, or an array of model instances.

Type
Promise

execute(sql, values)

This method is only available on the back-end.

Executes an SQLish statement on the model. To execute a raw sql statement, see Models#execute.

For example, on the back-end:

TestController.prototype.getTest = function() {
    return this.models.Test.execute('SELECT * form tests');
};
Parameters:
Name Type Description
sql String

SQLish statement.

values Array

An array of values

Returns:

Resolves with an array of model instances. Even if the result is one model instance, an array is returned with just one model instance.

Type
Promise

exists(whereMap)

Returns true if the model instance exists, or false otherwise. See Model#count.

Parameters:
Name Type Description
whereMap Dictionary

The where clause to add. See Model#find.

Returns:

Boolean.

Type
Promise

find(whereMap, optionsMap)

Finds one or more model instances.

For example, given the following User model:

function User() {
    this.name = [this.String];
    this.age = [this.Integer];
}
app.model(User);

In a controller in the client-context, to fetch up to 123 user's named "Martijn":

function MyController(UserModel) {
    UserModel.find({name: 'Martijn'}, {limit:123})
        .then(function(users) {
            //
        });
}
app.controller(MyController);

The same example in a controller in the server-context:

MyController.prototype.getMartijn = function() {
    return this.models.User.find({name:'Martijn'}, {limit: 123});
};

The same example REST-style over HTTP:

GET /api/users?name="Martijn"&$options={"limit":123}
Parameters:
Name Type Description
whereMap Dictionary

The where clause.

optionsMap Dictionary

Additional options for finding model instances, for example, ordering or selecting specific properties.

Properties
Name Type Description
limit Number

Limits the number of model instances returned. This does not limit the number of associations returned. For example, if you have a User model with 3000 auto-fetched projects associated to it, all 3000 projects will be fetched even if you set the limit to 100. There is currently no way to limit the number of auto-fetched associations returned.

skip Number

Skips the first number of model instances. This does not affect the associations.

orderBy Dictionary:.<String:, Mixed:>

Orders the model instances. The value should be a dictionary with property name and value pairs. The value of a pair can either be a string (DESC, or ASC) or a number (-1 and lower for DESC and 0 and higher ASC).

groupBy String | Array:.<String:>

The property name(s) to group by.

select Array:.<String:>

The properties to select. By default all properties are selected. If you specify an array only those properties are selected.

This is useful if you want to limit the number of properties to fetch of the model and it's associations.

To limit the properties to only name and id of the User model, see the example below. The id property is always included automatically.

models.User.find({}, {select:['name']});

If the property is an non-auto fetched association, the association is not fetched automatically. To fetch non-auto fetched associations, use the optionsMap.associations key.

You also need to specify the properties of any auto-fetched associations, else only their id property is returned. You can do this via the dot notation. For example, given a User model with a one-to-many projects association:

models.User.find({name: 'Martijn'}, {select:['name', 'projects.name']})
    .then(function(user) {
        // user
    });

You can also select all properties of an association by supplying a *:

models.User.find({name: 'Martijn'}, {select:['name', 'projects.*']})
    .then(function(user) {
        // user
    });

Please note if you try to access properties on a model instance not in the select list, the property's value will be undefined.

associations Array

An array of property names of the associations to fetch. This is useful if you need an association but it's not configured as auto fetch (see PropertyTypes#AutoFetch).

autoFetchDepth Number

The depth of associations of associations to fetch (if set to auto fetch). By default this is set to 5.

Returns:

Resolves with an array of model instances. If no model instances are found, with an empty array is resolved.

Type
Promise

findMe(request)

Returns the currently authenticated model instance, or null if not authenticated. Only returns a model instance if Model#authorize is previously called, otherwise this method returns null.

For example, on the client-side:

function UserController(UserModel) {
    UserModel.getMe()
        .then(funcion(user) {
            //
        });
}
app.controller(UserModel);

On the back-end side:

app.get('/users/me', function(UserModel, request) {
    return UserModel.getMe(request);
});

Only available on an authenticator model. To define an authenticator model, have a look at PropertyTypes#Authenticate.

Parameters:
Name Type Description
request express.request

Required in the back-end. The current request.

findOne(whereMap, optionsMap)

Finds one model instance.

Parameters:
Name Type Description
whereMap Dictionary
optionsMap Dictionary
Returns:
Type
Promise

findOrCreate(whereMap, setMap)

Finds a model instance, or creates one if it doesn't exist.

If a model instance is not found, one is created by merging the whereMap and the setMap. If both the maps create the same key(s), setMap the value of setMap is used.

This method simply executes Model#findOne followed by Model#create (if no model could be found). This method will be improved by using a writable CTE/WITH.

Parameters:
Name Type Description
whereMap Dictionary
setMap Dictionary

forgotPassword(authenticatingPropertyValue)

Starts the forgot password process. If a correct authenticatingPropertyValue is provided, for example a valid email of your user, create a reset password token.

When the forgot password succeeds, onForgotPassword is called on your authenticator. In here, you could, for example, send a reset password email.

Parameters:
Name Type Description
authenticatingPropertyValue String

The value of your authenticating property e.g. email.

getMe(request)

Returns the currently authenticated model instance or throws an error. See Model#findMe as well.

Parameters:
Name Type Description
request express.HTTPRequest

getOne()

Finds and resolves one model instance. See Model#findOne.

This method is similar to Model#findOne, expect that it always resolves with a model instance, or rejects the returned promise. This is useful in certain flows where you don't want to check if a model instance is null.

Returns:
Type
Promise

isPasswordBasedAuthenticator()

Returns if this model is the authenticator with a password property.

isShared()

Returns if this model is shared.

A shared model is available in every app. A shared model's migrations are created in the master app.

new()

Creates an empty model instance. This model instance is not persisted to the datastore until calling ModelInstance#save.

remove(whereMap)

Removes a model instance matching the where map.

Parameters:
Name Type Description
whereMap Dictionary
Returns:
Type
Promise

resetPassword(resetToken, newPassword, confirmPassword)

Resets the authenticator's password if forgot password was requested.

If the reset password succeeds, the onResetPassword method on your authenticator is called.

Parameters:
Name Type Description
resetToken String

The token generated from the forgotPassword method.

newPassword String

The new password.

confirmPassword String

The new password again.

Searches model instances based on query.

Parameters:
Name Type Description
searchText String

The search query e.g. "chicken" or "vegetable soup".

optionsMap Dictionary
privateMap Dictionary

signOut()

Signs out the current authenticator. To sign in a user, see Model#authorize.

For example, the below signs out a currently signed in user:

function AccountController($scope, UserModel, $location) {
    $scope.signOut = function() {
        return UserModel.signOut()
            .then(function() {
                $location.path('/');
            });
    };
}
app.controller(AccountController);

This method is only available on the authenticator model.

stream(whereMap, optionsMap)

Creates and returns a StreamInstance on this model.

A stream finds and returns all model instances matching whereMap. A stream finds model instances similar to Model#find and adds the model instances to the stream. But when new model instances get created, or updated, which match whereMap these new or updated model instances will be added to the stream.

var stream = ItemModel.stream({karma: {$gt: 10}});

// Adds an event listener to the changed event. Added and removed are two more events which can be useful. close is the last event which gets emitted once the stream gets closed.
var off = stream.on('changed', function(item) {
    // item was just added to the stream
});

// If we want to unregister the event listener, we can call off().
// stream.isLoading indicates whether the initial set of model instances have been loaded.
// stream.error if an error occured while loading.
// stream.results the array of model instances.

$scope.$on('$destroy', function() {
    // Closes the stream and removes all event listeners.
    stream.close();
});

This method is available on the front-end. This method is not yet available on the back-end.

Parameters:
Name Type Description
whereMap Dictionary

The where map. See Model#find.

optionsMap Dictionary

The options to set e.g. limit. See Model#find.

Returns:

A stream object which contains a results property containing all the model instances.

Type
Object

update(whereMap, setMap, optionsMap)

Updates model instances.

Parameters:
Name Type Description
whereMap Dictionary | String
setMap Dictionary
optionsMap Dictionary

Additional options to provide, similar to Model#find.

Properties
Name Type Description
limit Number

Limits the number of instances to update to limit.

skip Number

Skips the first skip number of instances to update.

orderBy Dictionary:.<String:, Mixed:>

Orders the model instances to update. Please note: while using this works properly in combination with the skip and limit option, the returned model instances are returned in the correct order.

Returns:

Returns an array of model instances.

Type
Promise

updateFunction()

Finds one or more model instances and updates them by invoking updateFunction for every instance. updateFunction uses dependency injection.

This should be considered a slow approach to updating model instances, but is a convenient method to update many model instances with a dependency injection-aware method. Especially when implemented in a migration during the release stage.

Consider a User model with slug properties which we want to update:

UserModel.updateFunction({slug:''}, function(user, SlugService) {
    user.slug = SlugService.slugify(user.name);
});

See Model#find for additional information. This method is not isomorphic and is only available on the back-end.

updateOne(whereMapOrId, setMap)

Updates model instance with a limit of 1 and returns 1 model instance.

Parameters:
Name Type Description
whereMapOrId Dictionary | String

Either a where map or UUID of the model instance.

setMap Dictionary

The models to set.

Returns:

Resolves with 1 model instance.

Type
Promise

updateOrCreate(whereMap, setMap)

Either updates a model instance, or creates a new model instance if not model exists.

This method simply executes Model#updateOne followed by Model#create if no model could be updated. This method will be improved by using a writable CTE/WITH.

Parameters:
Name Type Description
whereMap Dictionary
setMap Dictionary

Do you have any questions or comments on this page? Start a discussion below.

comments powered by Disqus
Subscribe to our list to receive the latest updates on Node on Fire