Defining a Model

Alexey Gordeyev edited this page Jan 1, 2016 · 10 revisions

Back to Overview

Define Model

Models are defined through the Schema interface.

// define models
var Post = schema.define('Post', {
    title:     { type: schema.String,  limit: 255 },
    content:   { type: schema.Text },
    params:    { type: schema.JSON },
    date:      { type: schema.Date,    default: Date.now },
    published: { type: schema.Boolean, default: false, index: true }
});

// simplier way to describe model
var User = schema.define('User', {
    name:         String,
    bio:          schema.Text,
    approved:     Boolean,
    joinedAt:     Date,
    age:          Number
});

Create CaminteJS Models in few minutes with online model creator.

Define Indices

// Add single-column index
var User = schema.define('User', {
    email:     { type: schema.String, "null": false, unique: true },
    name:      { type: schema.String, "null": false, limit: 255, index: true },
    content:   { type: schema.Text },
    params:    { type: schema.JSON },
    date:      { type: schema.Date,   default: Date.now },
});

// Add multi-column index
var User = schema.define('User', {
    email:          { type: schema.String, "null": false },
    name:           { type: schema.String, "null": false },
    birthDate:      { type: schema.Date },
    pendingPeriod:  { type: schema.Number, default: 0 },
    createdByAdmin: { type: schema.Boolean, default: 1 }
}, {
    indexes: {
        idx_1: {
            columns: 'email, createdByAdmin'
        },
        idx_2: {
            columns: 'name'
        }
    }
});

Define Primary Keys

var Student = schema.define("Student", {
    stuID: { type: schema.Number },
    school: { type: schema.String }
}, {
    primaryKeys: ["stuID"]
});

Accessing a Model

// models also accessible in schema:
schema.models.User;
schema.models.Post;