💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 定义模型 > 译者:[飞龙](https://github.com/wizardforcel) > 来源:[Defining Models](https://github.com/dresende/node-orm2/wiki/Defining-Models) 在[连接](1. Connecting to Database.md)之后,你可以使用连接对象(`db`)来定义你的模型。你需要指定模型的名称,一个用于描述的属性和一些(可选的)选项。下面是一个简短的例子: ``` var Person = db.define('person', { id: {type: 'serial', key: true}, // the auto-incrementing primary key name: {type: 'text'}, surname: {type: 'text'}, age: {type: 'number'} }, { methods : { fullName: function() { return this.name + ' ' + this.surname; } } }); ``` 这个模型叫做`person`(通常也是数据库里面表的名称),它有三个属性(`name`和`surname`为文本,`age`为数值)。如果你自己不指定任何键的话,默认的`id: { type: 'serial', key: true }`会添加进来。在这个例子中,有个模型方法叫做`fullName`。下面是这个模型的使用方法的示例: ``` Person.get(73, function(err, person) { if (err) throw err; console.log('Hi, my name is ' + person.fullName()); }); ``` 这会获取`id=73`的`person`对象,并且打印出它的名字和姓氏。其它类型的可用属性请见[这里](3.1 Model Properties.md)。 ## API ``` /** * @param {Object} props Property definitions * @param {Object} opts Options */ db.define(props, opts) ``` `db.define()`接收的第一个对象(第二个参数)被称为属性对象,它定义了所有的[属性](3.1 Model Properties.md)。 第二个对象指定了额外的选项: | 选项名称 | 类型 | 描述 | | --- | --- | --- | | `collection` | `String` | 覆写数据库中表的名称 | | `methods` | `Object` | 模型实例上的额外方法,它会被设置到实例上。 | | `hooks` | `Object` | 用户定义的[钩子或回调](3.3 Model Hooks.md) | | `validations` | `Object` | 用户定义的[验证器](3.2 Model Validations.md) | | `id` | `Array` | 为了支持在`properties`上设置`key: true`而不提倡使用 | | `cache` | `Boolean` | 允许你开启或者禁用单例行为。它叫做`cache`,但是和缓存毫无关系。 | | `autoSave` | `Boolean` | 不推荐。在属性修改时自动保存模型。 | | `autoFetch` | `Boolean` | 是否自动获取关联 | | `autoFetchLimit` | `Number` | 自动获取关联的深度 | | `cascadeRemove` | `Boolean` | 删除实例时是否要删除关联 |