Skip to content
Arek W edited this page May 26, 2014 · 10 revisions

After [connecting](Connecting to Database), you can use the connection object (db) to define your models. You need to specify the name of the model, a specification of the properties and options (optional). Here's a small example:

var Person = db.define('person', {
  id      : { type: "serial", key: true }, // autoincrementing primary key
  name    : { type: "text" },
  surname : { type: "text" },
  age     : { type: "number" }
}, {
  methods : {
    fullName: function () {
      return this.name + " " + this.surname;
    }
  }
});

The model is called person (which is usually the name of the table in the database), it has 3 properties (name and surname as text and age as number). A default id: { type: 'serial', key: true } property is added if you don't specify any keys yourself. In this example there is a model method called fullName. Here's an example of the usage of this model:

Person.get(73, function (err, person) {
  if (err) throw err;

  console.log("Hi, my name is %s", person.fullName());
});

This would get person with id=73 and print it's name and surname. There are other types of [properties available](Model Properties).

API

/**
 * @param {Object} props Property definitions
 * @param {object} opts Options
 */
db.define(props, opts)

The first object accepted by db.define() is referred to as the properties object. It defines all the properties. The second specifies extra options.

option name option description
collection String Lets you overwrite the table name in the database
methods Object Extra methods to create on model instances. this will be the instance.
hooks Object User defined hooks/callback.
validations Object User defined validations
id Array Deprecated in favour of setting key: true on properties
cache Boolean Allows you to disable/enable singleton behaviour. It's called cache but it's not cache.
autoSave Boolean Don't recommend using this
autoFetch Boolean Autofetch associations which were defined with autoFetch true. I think.
autoFetchLimit Number How many levels deep to autofetch
cascadeRemove Boolean ?
Clone this wiki locally