Skip to content
Arek W edited this page Jan 11, 2022 · 9 revisions

Models and some associations can have one or more properties. Every property has a type and a couple of optional settings you can choose (or leave the default).

Types

The supported types are:

  • text: A text string;
  • number: A floating point number. You can specify size: 2|4|8.
  • integer: An integer. You can specify size: 2|4|8.
  • boolean: A true/false value;
  • date: A date object. You can specify time: true
  • enum: A value from a list of possible values;
  • object: A JSON object;
  • point: A N-dimensional point (not generally supported);
  • binary: Binary data.
  • serial: Auto-incrementing integer. Used for primary keys.
  • uuid: Only supported by PostgreSQL.

Each type can have additional options. Here's a model definition using most of them:

var Person = db.define("person", {
	name    : { type: "text", size: 50 },
	surname : { type: "text", defaultValue: "Doe" },
	male    : { type: "boolean" },
	vat     : { type: "integer", unique: true },
	country : { type: "enum", values: [ "USA", "Canada", "Rest of the World" ] },
	birth   : { type: "date", time: false }
});

All types support required (boolean), unique (boolean) and defaultValue (text). Text type also supports maximum size of string (number) and big (boolean - for very long strings). Number type is a float, size (number - byte size) and unsigned (boolean). Date type supports time (boolean).

Note that 8 byte numbers have limitations.

If you're using default options, you can use native types to specify property types:

var Person = db.define("person", {
	name    : String,
	male    : Boolean,
	vat     : Number, // FLOAT
	birth   : Date,
	country : [ "USA", "Canada", "Rest of the World" ],
	meta    : Object, // JSON
	photo   : Buffer  // binary
});

Mapping ORM fields to differently named database columns

var Person = db.define("person", {
	name    : { type: 'text', mapsTo: 'fullname' }
});

ORM property name maps to person table column fullname.

Custom types

You can add your own types to ORM like so:

db.defineType('numberArray', {
  datastoreType: function(prop) {
    return 'TEXT'
  },
  // This is optional
  valueToProperty: function(value, prop) {
    if (Array.isArray(value)) {
      return value;
    } else {
      return value.split(',').map(function (v) {
        return Number(v);
      });
    }
  },
  // This is also optional
  propertyToValue: function(value, prop) {
    return value.join(',')
  }
});
var LottoTicket = db.define('lotto_ticket', {
  numbers: { type: 'numberArray' }
});

There are more advanced custom types available to aid in using things like PostGIS. See this spec.

Clone this wiki locally