基本模型

此示例显示如何在 Sails.js 中定义简单模型

你可以通过键入生成空模型文件

sails generate model car

你会在 api/models/找到新文件 Car.js

接下来,你将填写一些详细信息。

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']
    }

  }

};

上面的示例几乎使用了所有可能的模型选项,如下所述。

tableName

此参数定义将在数据库中创建的表的名称。如果未定义,将使用模型名称(在此示例中为 car)。

2.连接

此特定定义用于模型的数据库连接。该连接的详细信息在 config/connections.js 内的 mongodb 键下定义。这是连接的格式:

mongodb : {

  // The driver that connect our models with the database
  adapter : '<adapter>',

  // The database parameters
  user : '<username>',
  port : <port>,
  host : '<host>',
  database : '<database>'

}

3.属性

每个属性都引用模型的数据库表中的列。在此示例中,将创建九列。每列可以配置一个或多个以下键:

  • type :列的数据类型。此页面列出了所有可用的类型。
  • unique :如果为 true,则尝试创建与此列中的值相同的对象时,将发生错误。
  • primaryKey :如果为 true,则列将作为主键。
  • autoIncrement :序列将与列关联,并且自动可递增数字从 0 开始。
  • size :列的最大长度。
  • required :如果为 true,则不能为 null。
  • columnName :这将配置数据库中的列,默认为属性名称。
  • 枚举 :我们可以为属性设置一组可能的选项。