-
Notifications
You must be signed in to change notification settings - Fork 8
Create a Model
Alexey Gordeyev edited this page Jan 22, 2014
·
13 revisions
How to create Model via CLI TrinteJS MVC
- Command format
- Create a Model
- Create a Model with fields
- Created a Model example
- Model Tuning
- Setup Model Validations
- Setup Models Relationships
- Field types
format: trinte -g model [model name] [field(s)]
// Create Post Model
$ trinte -g model Post
// create User Model with fields name, email, password, active: Boolean
$ trinte -g model User name email password active:boolean
Generated files, path like that:
.
|
`-- app
`-- models
|-- User.js
`-- ...
/**
* Define User Model
* @param {Object} schema
* @return {Object}
**/
module.exports = function(schema){
var User = schema.define('user', {
active : { type: Boolean },
name : { type: String },
email : { type: String },
password : { type: String }
});
return User;
};Following are all valid field types.
String
Number
Date
Boolean
Text
Learn more on CaminteJS.
module.exports = function(schema){
var Post = schema.define('Post', {
active : { type : Boolean, 'default' : 1, index : true },
title : { type: String, limit: 255, require : true },
content : { type: schema.Text },
tags : { type: schema.JSON },
created: { type: Date, default: Date.now, index: true }
});
return Post;
};Learn more on CaminteJS.
set validation in ModelsHelper file, location in project /app/helpers/ModelsHelper.js
User.validatesPresenceOf('name', 'email')
User.validatesLengthOf('password', {min: 5, message: {min: 'Password is too short'}});
User.validatesInclusionOf('gender', {in: ['male', 'female']});
User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']});
User.validatesNumericalityOf('age', {int: true});
User.validatesUniquenessOf('email', {message: 'email is not unique'});usage in controller.
user.isValid(function (valid) {
if (!valid) {
user.errors // hash of errors {attr: [errmessage, errmessage, ...], attr: ...}
}
});Learn more on CaminteJS.
set relationships in ModelsHelper file, location in project /app/helpers/ModelsHelper.js
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
// creates instance methods:
// user.posts(conds)
// user.posts.build(data) // like new Post({userId: user.id});
// user.posts.create(data) // build and save
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
// creates instance methods:
// post.author(callback) -- getter when called with function
// post.author() -- sync getter when called without params
// post.author(user) -- setter when called with objectusage in controller.
// work with models:
var user = new User;
user.save(function (err) {
var post = user.posts.build({title: 'Hello world'});
post.save(console.log);
});Learn more on CaminteJS.