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

Class: ModelInstance

ModelInstance

new ModelInstance(model, row, changes, id, hookname, isPartial, isShallow)

A model instance represents one or multiple rows in the database. These instances are usually the return value(s) of Model#find, Model#create and Model#update methods.

This calls the beforeLoad hook when initialization starts and calls afterLoad when initializations finishes. To declare a hook, declare a method with the hook name on the model's prototype. For example, this creates an afterCreate hook on a User model:

function User() {
    this.email = [this.String, this.Authenticate];
    this.type = [this.String];
    this.posts = [this.HasMany(this.models.Post)];
}
app.model(User);

User.prototype.afterCreate = function() {
    // Gets executed whenever a new model instance is created.
};
Parameters:
Name Type Description
model Model

The model the instance belongs to.

row Dictionary

A map of all column-value pairs from the database.

changes Dictionary

A map of property-value pairs set by the caller.

id String

The instance primary key's value, if known.

hookname String

The name of the hook to execute after the model instance is created.

isPartial Boolean

true if the model instance is partial. A partial model instance is returned from a create, update, delete or execute action.

isShallow Boolean

If set to true the model instance does not dynamically create any methods. This is useful when you don't want to do anything with the model instances directly and don't need to overhead of creating dynamic methods.

Methods

_getValue()

Returns the value for given key. Useful in shallow models where the magic property getters and setters are not automatically created.

addAssociation(property, modelInstance)

Adds modelInstance as association of property.

Parameters:
Name Type Description
property Property

The property of the association the model instance is added to.

modelInstance ModelInstance

The model instance to be added to the association.

callHooks(hookNames)

Internally calls the hooks.

The following hooks are supported:

beforeLoad

Before the model instance gets loaded. Please note: you cannot return a promise here to block the loading of the model.

afterLoad

After a model instance is loaded this hook is called. Please note: you cannot return a promise here to block the loading of the model.

beforeSave

Before the model is saved: either newly created or updated.

afterSave

invoked after the model instance successfully saved (either a new instance or updated instance).

afterCreate

invoked after a new instance is created.

afterUpdate

Invoked after a model instance is updated, either after ModelInstance#save or Model#update.

Parameters:
Name Type Description
hookNames Array

List of hook names to invoke the methods of.

cancel()

Clears all changes from the model. This erases any unsaved changed.

changePassword(currentPassword, newPassword, confirmPassword)

Changes the instance's password. This method is only available on authenticator model instances.

Parameters:
Name Type Description
currentPassword String

The current password

newPassword String

A new password

confirmPassword String

Confirm password. Should be the same as newPassword.

checkProperties()

Internally checks all the values of the properties, applies any transform methods, if neccesary, and sets any default values, if specified.

configureProperty(property)

Adds property property to the model instance. This configures accessor methods of the property and any relationships. This is invoked when constructing the model instance right after beforeLoad hook and before afterLoad hook.

Parameters:
Name Type Description
property Property

The property to configure.

consumeRow(row)

Parameters:
Name Type Description
row Dictionary

A row from the datastore.

To Do:
  • This method and ModelInstance#parseRow have similar code. They should be merged. It's not DRY. Reads the information of a datastore's row and parses the row if it's considerd part of this model instance.
Returns:

Returns true if the row is consumed by this model instance, false if not.

Type
Boolean

createAssociations(associations)

Parses the associations dictionary and creates model instances for every association.

Each value in the dictionary is a dictionary of column name-value pairs. An association only has one dictionary, because the associations are added per row. This method generally gets called multiple times per model instance (depending on the number of associations).

Parameters:
Name Type Description
associations Dictionary

The dictionary with the association names as keys.

Returns:

Returns true if a valid association is added, false otherwise.

Type
Boolean

getLoginToken()

Either finds an existing login token if it's less than 1 week old. If no tokens can be found, or the tokens are older than a week, a new token is created.

By default, tokens expire after two weeks.

parseRow(row)

Parses the given row and any associations it finds.

Parameters:
Name Type Description
row Dictionary

Map of column name-value pairs.

remove()

Removes the model instance.

resolvePromises()

Resolves all promises set on the model instance.

This makes it possible to set unresolved promises as values of properties. This method is called during saving. If any of the promises rejects, the saving of the model rejects, too.

For example, consider creating a project instance with an owner property:

this.models.Project.create({
    name: 'Test Project',
    owner: this.models.User.findOne({name: 'Martijn'})
});

save()

Saves the model instance. This either creates a new model instance, or updates an existing model instance.

this.models.Post.create({
        title: 'The Adventures of Huckleberry Finn',
      createdAt: new Date()
 })
 .then(function(post) {
     post.title = 'Confessions of a Shopaholic'
     return post.save();
    })
Returns:
Type
Promise

toJSON()

Convert the instance to a simple Dictionary when JSON#stringify is called.

All auto-fetched assocations are included in the returned dictionary, see PropertyTypes#AutoFetch on how to configure associations to be auto-fetched.

A _type key is also included. The _type's value is the name of the model. This is used in the client-side parser to allocate and initialize the correct model instance.

Private properties, like a password, are not included in the returned dictionary, see PropertyTypes#Private on how to declare private properties.

Returns:

The JSON representation of the model instance.

Type
Dictionary

toQueryValue()

toQueryValue is executed by Table to convert a model instance to a valid parameter in a query.

Returns:
Type
String

validateChanges()

To Do:
  • Replace this by PropertyTypes#Validate. Validates all set property values. This calls a validate method named after the property's name prefixed with validate. If the method returns a truthy value the property value is considered valid. If anything else the value is considered invalid. This method is invoked before saving the model in ModelInstance#save.
Returns:
Type
Promise

validateHash(hashedPropertyName, password)

Validates a hashed property, see PropertyTypes#Hash.

return UserModel.getOne({email: 'martijn@ff00ff.nl'})
    .then(function(instance) {
     return instance.validateHash('password', 'my password');
 }).then(function(correct) {
     if(correct) {
         // Correct!
       }
        else {
        throw new Error('Incorrect password provided.');
     }
 });

This methods returns a promise which resolved to true if the password is correct. false if the password is incorrect.

Parameters:
Name Type Description
hashedPropertyName String

The name of the property with a hash method.

password String

The plaintext password.

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