本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
1. Model使用:
1.1. Schema使用
schema:类似于mysql中建表操作,规定一个表中有哪些字段,哪些字段有怎样的约束
example:
const child = new Schema({ name: String });
const schema = new Schema({ name: String, age: Number, children: [child] });
const Tree = mongoose.model('Tree', schema);
// setting schema options
new Schema({ name: String }, { _id: false, autoIndex: false })
// 例子来源于mongoose官方文档
Schema中的有效类型,可以添加自定义类型:
具体类型的属性可点击属性连接进入官方文档
若存在嵌套类型时,将嵌套的类型定义为一个新的schema,再使用type:schema调用
以下为所有字段属性,常用属性用粗体表示
| 属性名 | 类型 | 描述 | |
|---|---|---|---|
| required | boolean | 若为true,则表示该字段为必须 | |
| default | any | function | 若为值,则表示该字段的默认值,若为函数,则函数的返回值作为字段的默认值 |
| select | Boolean | 指定查询的默认projections | |
| validate | function | 为该字段添加一个验证函数 | |
| get | function | 使用Object.defineProperty()定义此属性的自定义 getter. | |
| set | function | 使用Object.defineProperty()定义此属性的自定义 setter. | |
| alias | string | mongoose >= 4.10.0可使用,定义一个别名 | |
| immutable | boolean | 若为true,字段将不可改变 | |
| transform | function | Mongoose在调用Document#toJSON() function时调用该函数 | |
| ref | string | 该属性类似于mysql中的外键,设置该属性的值为其他表名,数据库中存该表下的某一条数据,即可以在之后进行连表操作 |
来源:mongoosejs.com/docs/schema…
例
const numberSchema = new Schema({
integerOnly: {
type: Number,
get: v => Math.round(v),
set: v => Math.round(v),
alias: 'i'
}
});
const Number = mongoose.model('Number', numberSchema);
const doc = new Number();
doc.integerOnly = 2.001;
doc.integerOnly; // 2
doc.i; // 2
doc.i = 3.001;
doc.integerOnly; // 3
doc.i; // 3
若想要在表中自动加入创建时间和修改时间可使用以下代码
const testSchema = new Schema({
name: { type: String }
},
{
timestamps: { createdAt: 'createAt', updatedAt: 'updateAt' }
}
) // timestamps里的值名称可以随意修改
1.2. 创建model
创建第一个model:
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
2. Service使用:
2.1. 创建service:
export class TankService extends Service {
public model;
constructor(ctx: Context) {
super(ctx);
this.ctx = ctx;
this.model = ctx.model.Tank;
}
async create(){
this.ctx.model.Tank.create()
}
}
即可使用mongoose内置的增删改查方法
推荐封装一个公共class,将公共的service方法写入该类,以后使用时可以直接继承该类来使用公共方法