This example shows how to define a simple model in Sails.js
You can generate an empty model file by typing
sails generate model car
You'll find the new file Car.js
in api/models/
.
Next, you fill in some details.
modules.exports = {
tableName : 'cars',
connection : 'mongodb',
attributes : {
id : {
type : 'integer',
unique : true,
primaryKey : true,
autoIncrement : true
},
brand : {
type : 'string',
size : 25
},
description : {
type: 'text',
defaultsTo : ''
},
price : {
type : 'float',
required : true
},
seats : {
type : 'integer'
},
sell_date : {
type : 'datetime'
},
has_cooler : {
type : 'boolean',
columnName : 'cooler'
},
chassis_number : {
unique : true,
type : 'string'
},
color : {
type : 'string',
enum: ['white', 'red', 'black']
}
}
};
The example above uses nearly every possible model option, which are explained below.
1. tableName
This parameter defines the name of the table that will be created in the database. If not defined, the model name will be used (car
in this example).
2. connection
This particular defines the database connection used for the model. The details of that connection are defined under the mongodb
key inside config/connections.js
. Here's the format of a connection:
mongodb : {
// The driver that connect our models with the database
adapter : '<adapter>',
// The database parameters
user : '<username>',
port : <port>,
host : '<host>',
database : '<database>'
}
3. attributes
Each attribute references a column in the database table for the model. In this example, nine columns will be created. Each column can be configured with one or more of the following keys: