CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-loopback

LoopBack is a highly-extensible, open-source Node.js framework that enables developers to create dynamic end-to-end REST APIs with minimal coding.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

models.mddocs/

Model System

LoopBack's comprehensive model system provides data modeling, validation, relationships, and persistence capabilities through the Model and PersistedModel base classes, along with a registry system for model management.

Capabilities

Model Creation and Management

Create and configure models with properties, validations, and relationships.

/**
 * Create a new model class
 * @param {string} name - Model name
 * @param {Object} properties - Model properties definition  
 * @param {Object} options - Model configuration options
 * @param {string} options.base - Base model to extend from
 * @param {Object} options.relations - Model relationships
 * @param {Object} options.validations - Validation rules
 * @param {Object} options.settings - Model settings
 * @returns {Function} Model constructor
 */
loopback.createModel(name, properties, options);

/**
 * Alternative config object approach
 * @param {Object} config - Model configuration
 * @param {string} config.name - Model name
 * @param {Object} config.properties - Properties definition
 * @param {Object} config.relations - Relationships
 * @param {Object} config.base - Base model name
 * @returns {Function} Model constructor
 */
loopback.createModel(config);

/**
 * Configure an existing model
 * @param {Function} ModelCtor - Model constructor to configure
 * @param {Object} config - Configuration to apply
 * @param {DataSource} config.dataSource - Data source to attach to
 * @param {Object} config.relations - Relations to add/update
 */
loopback.configureModel(ModelCtor, config);

/**
 * Find a model by name
 * @param {string} modelName - Model name to find
 * @returns {Function|null} Model constructor or null if not found
 */
loopback.findModel(modelName);

/**
 * Get a model by name (throws if not found)
 * @param {string} modelName - Model name to get
 * @returns {Function} Model constructor
 * @throws {Error} If model not found
 */
loopback.getModel(modelName);

/**
 * Find model by base model type
 * @param {Function} modelType - Base model constructor
 * @returns {Function} Subclass if found, or base class
 */
loopback.getModelByType(modelType);

Usage Examples:

// Create a basic model
const Book = loopback.createModel('Book', {
  title: { type: String, required: true },
  author: String,
  isbn: { type: String, index: true },
  publishedDate: Date,
  price: Number
});

// Create model with relationships and options
const Author = loopback.createModel('Author', {
  name: { type: String, required: true },
  email: { type: String, index: { unique: true } },
  bio: String
}, {
  relations: {
    books: {
      type: 'hasMany',
      model: 'Book',
      foreignKey: 'authorId'
    }
  },
  validations: {
    email: { format: 'email' }
  }
});

// Alternative config approach
const Review = loopback.createModel({
  name: 'Review',
  properties: {
    rating: { type: Number, min: 1, max: 5 },
    comment: String,
    createdAt: { type: Date, default: Date.now }
  },
  relations: {
    book: {
      type: 'belongsTo',
      model: 'Book',
      foreignKey: 'bookId'
    }
  }
});

// Configure existing model
loopback.configureModel(Book, {
  dataSource: loopback.memory(),
  relations: {
    reviews: {
      type: 'hasMany',
      model: 'Review',
      foreignKey: 'bookId'
    }
  }
});

Base Model Class

The foundation Model class provides event system, validation, and basic model functionality.

/**
 * Base Model constructor
 * @param {Object} data - Initial model data
 */
function Model(data);

// Static methods
/**
 * Extend the model to create a subclass
 * @param {string} className - Name for the new model class
 * @param {Object} properties - Properties for the new model
 * @param {Object} settings - Settings for the new model
 * @returns {Function} New model constructor
 */
Model.extend(className, properties, settings);

/**
 * Setup the model (called automatically)
 */
Model.setup();

/**
 * Define a remote method on the model
 * @param {string} name - Method name
 * @param {Object} options - Remote method options
 * @param {Object} options.accepts - Input parameters
 * @param {Object} options.returns - Return value description
 * @param {Object} options.http - HTTP configuration
 */
Model.remoteMethod(name, options);

/**
 * Disable a remote method
 * @param {string} name - Method name to disable
 * @param {boolean} isStatic - Whether method is static
 */
Model.disableRemoteMethod(name, isStatic);

/**
 * Register before remote hook
 * @param {string} name - Remote method name or pattern
 * @param {Function} fn - Hook function
 */
Model.beforeRemote(name, fn);

/**
 * Register after remote hook
 * @param {string} name - Remote method name or pattern
 * @param {Function} fn - Hook function
 */
Model.afterRemote(name, fn);

/**
 * Register after remote error hook
 * @param {string} name - Remote method name or pattern
 * @param {Function} fn - Hook function
 */
Model.afterRemoteError(name, fn);

/**
 * Check access permission for context
 * @param {Object} token - Access token
 * @param {*} modelId - Model instance ID
 * @param {Object} sharedMethod - Shared method
 * @param {Object} ctx - Access context
 * @param {Function} callback - Callback function
 */
Model.checkAccess(token, modelId, sharedMethod, ctx, callback);

/**
 * Get the attached application
 * @param {Function} callback - Callback function
 */
Model.getApp(callback);

// Instance methods
/**
 * Check if model instance is valid
 * @param {Function} callback - Callback function
 */
model.isValid(callback);

/**
 * Trigger model hooks
 * @param {string} actionName - Action name
 * @param {Function} work - Work function
 * @param {*} data - Hook data
 * @param {Function} callback - Callback function
 */
model.trigger(actionName, work, data, callback);

PersistedModel Class

Extends Model with database operations and CRUD functionality.

/**
 * PersistedModel constructor (extends Model)
 * @param {Object} data - Initial model data
 */
function PersistedModel(data);

// Instance methods
/**
 * Save the model instance
 * @param {Object} options - Save options
 * @param {Function} callback - Callback function
 */
instance.save(options, callback);

/**
 * Delete the model instance
 * @param {Function} callback - Callback function
 */
instance.destroy(callback);

/**
 * Update a single attribute
 * @param {string} name - Attribute name
 * @param {*} value - New value
 * @param {Function} callback - Callback function
 */
instance.updateAttribute(name, value, callback);

/**
 * Update multiple attributes
 * @param {Object} data - Attributes to update
 * @param {Function} callback - Callback function
 */
instance.updateAttributes(data, callback);

/**
 * Replace all attributes
 * @param {Object} data - New attribute values
 * @param {Function} callback - Callback function
 */
instance.replaceAttributes(data, callback);

/**
 * Reload instance from database
 * @param {Function} callback - Callback function
 */
instance.reload(callback);

/**
 * Check if instance is new (not saved)
 * @returns {boolean} True if new record
 */
instance.isNewRecord();

/**
 * Set the instance ID
 * @param {*} val - ID value
 */
instance.setId(val);

/**
 * Get the instance ID
 * @returns {*} ID value
 */
instance.getId();

/**
 * Get the ID property name
 * @returns {string} ID property name
 */
instance.getIdName();

Static CRUD Methods

Standard database operations available on PersistedModel classes.

/**
 * Create new model instance(s)
 * @param {Object|Object[]} data - Data for new instance(s)
 * @param {Function} callback - Callback function
 */
Model.create(data, callback);

/**
 * Update or insert model instance
 * @param {Object} data - Instance data (must include ID for updates)
 * @param {Function} callback - Callback function
 */
Model.upsert(data, callback);

/**
 * Find existing instance or create new one
 * @param {Object} filter - Filter to find existing instance
 * @param {Object} data - Data for new instance if not found
 * @param {Function} callback - Callback function
 */
Model.findOrCreate(filter, data, callback);

/**
 * Replace existing instance or create new one
 * @param {Object} data - Instance data (must include ID)
 * @param {Function} callback - Callback function
 */
Model.replaceOrCreate(data, callback);

/**
 * Update or insert with where condition
 * @param {Object} where - Where conditions for matching existing instance
 * @param {Object} data - Data for new instance if not found
 * @param {Function} callback - Callback function
 */
Model.upsertWithWhere(where, data, callback);

/**
 * Replace instance by ID
 * @param {*} id - Instance ID
 * @param {Object} data - New instance data
 * @param {Function} callback - Callback function
 */
Model.replaceById(id, data, callback);

/**
 * Find model instances
 * @param {Object} filter - Query filter
 * @param {Object} filter.where - Where conditions
 * @param {Object} filter.include - Relations to include
 * @param {string|string[]} filter.fields - Fields to select
 * @param {number} filter.limit - Limit results
 * @param {number} filter.skip - Skip results
 * @param {string|Object} filter.order - Sort order
 * @param {Function} callback - Callback function
 */
Model.find(filter, callback);

/**
 * Find single model instance
 * @param {Object} filter - Query filter (same as find)
 * @param {Function} callback - Callback function
 */
Model.findOne(filter, callback);

/**
 * Find model instance by ID
 * @param {*} id - Instance ID
 * @param {Object} filter - Additional filter options
 * @param {Function} callback - Callback function
 */
Model.findById(id, filter, callback);

/**
 * Check if instance exists
 * @param {*} id - Instance ID
 * @param {Function} callback - Callback function
 */
Model.exists(id, callback);

/**
 * Count model instances
 * @param {Object} where - Where conditions
 * @param {Function} callback - Callback function
 */
Model.count(where, callback);

/**
 * Update model instances
 * @param {Object} where - Where conditions
 * @param {Object} data - Data to update
 * @param {Function} callback - Callback function
 */
Model.update(where, data, callback);

/**
 * Update all matching instances (alias for update)
 * @param {Object} where - Where conditions
 * @param {Object} data - Data to update
 * @param {Function} callback - Callback function
 */
Model.updateAll(where, data, callback);

/**
 * Delete instance by ID
 * @param {*} id - Instance ID
 * @param {Function} callback - Callback function  
 */
Model.destroyById(id, callback);

/**
 * Delete all matching instances
 * @param {Object} where - Where conditions
 * @param {Function} callback - Callback function
 */
Model.destroyAll(where, callback);

Usage Examples:

// Create instances
Book.create({
  title: 'The Great Gatsby',
  author: 'F. Scott Fitzgerald',
  isbn: '978-0-7432-7356-5'
}, (err, book) => {
  console.log('Created:', book.id);
});

// Find with filter
Book.find({
  where: { author: { like: '%Fitzgerald%' } },
  include: 'reviews',
  limit: 10,
  order: 'publishedDate DESC'
}, (err, books) => {
  console.log('Found books:', books.length);
});

// Update instances
Book.updateAll(
  { author: 'F. Scott Fitzgerald' },
  { author: 'Francis Scott Fitzgerald' }, 
  (err, info) => {
    console.log('Updated:', info.count);
  }
);

Change Tracking and Replication

Methods for tracking changes and replicating data between models.

/**
 * Create a change stream for real-time updates
 * @param {Object} options - Stream options
 * @param {Function} callback - Callback function
 */
Model.createChangeStream(options, callback);

/**
 * Get changes since a checkpoint
 * @param {number} since - Checkpoint ID
 * @param {Object} filter - Optional filter
 * @param {Function} callback - Callback function
 */
Model.changes(since, filter, callback);

/**
 * Replicate changes to another model
 * @param {number} since - Checkpoint ID  
 * @param {Function} targetModel - Target model constructor
 * @param {Object} options - Replication options
 * @param {Function} callback - Callback function
 */
Model.replicate(since, targetModel, options, callback);

/**
 * Get the Change model for this model
 * @returns {Function} Change model constructor
 */
Model.getChangeModel();

/**
 * Get source ID for replication
 * @param {Function} callback - Callback function
 */
Model.getSourceId(callback);

Model Registry

/**
 * Model registry for managing models and data sources
 */
class Registry {
  /**
   * Create new registry instance
   */
  constructor();

  /**
   * Registry methods (same as loopback static methods)
   */
  createModel(name, properties, options);
  configureModel(ModelCtor, config);
  findModel(modelName);
  getModel(modelName);
  getModelByType(modelType);
  createDataSource(name, options);
  memory(name);
}

Model Configuration Types

/**
 * Model property definition
 */
interface PropertyDefinition {
  type: Function;              // Property type (String, Number, Date, etc.)
  required?: boolean;          // Whether property is required
  default?: any;              // Default value
  index?: boolean | Object;   // Index configuration
  unique?: boolean;           // Unique constraint
  min?: number;               // Minimum value (numbers)
  max?: number;               // Maximum value (numbers)
  length?: number;            // String length
  format?: string;            // Validation format
}

/**
 * Model relationship definition
 */
interface RelationDefinition {
  type: string;               // Relationship type: hasMany, belongsTo, hasOne, etc.
  model: string;              // Related model name
  foreignKey?: string;        // Foreign key property
  through?: string;           // Through model for many-to-many
  as?: string;               // Relationship alias
  options?: Object;          // Additional relationship options
}

/**
 * Model validation definition
 */
interface ValidationDefinition {
  [propertyName: string]: {
    presence?: boolean;
    length?: { min?: number; max?: number };
    format?: string | RegExp;
    inclusion?: { in: any[] };
    exclusion?: { in: any[] };
    uniqueness?: boolean;
    custom?: Function;
  };
}

docs

application.md

auth.md

datasources.md

index.md

middleware.md

models.md

tile.json