This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Modella Models Cheatsheet

A quick reference guide for Modella: minimalist JavaScript model framework, attribute definitions, validations, lifecycle events, and plugins.

· Published

[!NOTE] Archived Project: Modella is a historical minimalist model framework for Node.js and browser applications. For modern projects, tools like Zod or Prisma are standard.

Modella is a bare-bones data modeling library designed to be extended via plugins.

Model Definition

const Modella = require('modella');
const validators = require('modella-validators');

const User = Modella('User')
  .attr('id')
  .attr('name')
  .attr('email', { required: true })
  .use(validators);

// Custom validation rule
User.validate((user) => {
  if (!user.name()) {
    user.error('name', 'Name is required');
  }
});

Model Instances & Properties

// Instantiation
const user = new User({ name: 'Alice', email: '[email protected]' });

// Getters and Setters
user.name();               // -> "Alice"
user.name('Bob');          // Sets name to "Bob"
user.set({ name: 'Charlie' });

// State predicates
user.has('name');          // -> true
user.isNew();              // -> true (not yet saved)
user.isValid();            // Runs sync validators -> true/false

Lifecycle Events

// Persistence events
user.on('save', () => console.log('Saved'));
user.on('create', () => console.log('Created'));
user.on('remove', () => console.log('Removed'));

// Async hooks
user.on('saving', (instance, done) => {
  // Pre-save asynchronous hook
  done();
});

// Attribute change events
user.on('change', () => console.log('Attributes modified'));
user.on('change email', () => console.log('Email changed'));

Plugin Architecture

A Modella plugin is a higher-order function that decorates the model:

const TimestampsPlugin = () => {
  return (Model) => {
    Model
      .attr('createdAt')
      .attr('updatedAt');

    Model.on('saving', (record, done) => {
      const now = new Date();
      if (record.isNew()) record.createdAt(now);
      record.updatedAt(now);
      done();
    });

    return Model;
  };
};

User.use(TimestampsPlugin());

References

Related topics