译者:飞龙
在连接之后,你可以使用连接对象(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
对象,并且打印出它的名字和姓氏。其它类型的可用属性请见这里。
API
/**
* @param {Object} props Property definitions
* @param {Object} opts Options
*/
db.define(props, opts)
db.define()
接收的第一个对象(第二个参数)被称为属性对象,它定义了所有的属性。
第二个对象指定了额外的选项:
选项名称 | 类型 | 描述 |
---|---|---|
collection |
String |
覆写数据库中表的名称 |
methods |
Object |
模型实例上的额外方法,它会被设置到实例上。 |
hooks |
Object |
用户定义的钩子或回调 |
validations |
Object |
用户定义的验证器 |
id |
Array |
为了支持在properties 上设置key: true 而不提倡使用 |
cache |
Boolean |
允许你开启或者禁用单例行为。它叫做cache ,但是和缓存毫无关系。 |
autoSave |
Boolean |
不推荐。在属性修改时自动保存模型。 |
autoFetch |
Boolean |
是否自动获取关联 |
autoFetchLimit |
Number |
自动获取关联的深度 |
cascadeRemove |
Boolean |
删除实例时是否要删除关联 |