Models provide Node and REST APIS for interacting with data sources, performing data validation, and representing relationships among data.

Page Contents

Overview

A LoopBack model is a JavaScript object with both Node and REST APIs that represents data in backend systems such as databases. Models are connected to backend systems via data sources. You use the model APIs to interact with the data source to which it is attached. Additionally, you can add functionality such as validation rules and business logic to models.

Every LoopBack application has a set of predefined built-in models such as User, Role, and Application. You can extend built-in models to suit your application’s needs.  

Additionally, you can define your own custom models specific to your application. You can create LoopBack models several different ways:

These methods all create a Model definition JSON file that defines your model in LoopBack.

You can also create and customize models programmatically using the  LoopBack API, or by manually editing the model definition JSON file. In most cases, you shouldn’t need to use those techniques to create models, but you generally will use them to modify and customize models.

Once you’ve created a model, you can customize it to suit your needs, and also add data validation and create relationships among models.

Models come with a standard set of REST endpoints for create, read, update, and delete (CRUD) operations on model data. You can customize a model’s endpoints; see Exposing models over REST.

Getting a reference to a model in JavaScript

The way that you get a reference (or “handle”) to a model in JavaScript code depends on where the code is.

In model JavaScript file

In the model JavaScript file, the model is passed into the top-level function, so the model object is available directly; for example for a “customer” model:

/common/models/customer.js

module.exports = function(Customer) {
  // Customer object is available 
  //...
}

In a boot script

In a boot script, use the app.models object to get a reference to any model; for example:

/server/boot/script.js

module.exports = function(app) {
  var User = app.models.user;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;
  var Team = app.models.Team;
  //...
}
Tags: models