egg 学习之路(1)
我是使用egg来搭建后端,前端使用的react,数据库是mongodb
初步学习egg的搭建及使用
开始呢,是从egg的官网,开始学习,使用脚手架快速搭建。学习如何制作中间件,然后学习Controller,router, router中路由为get时,获取客户端传过的参数要用 ctx.query router中路由为post时,获取客户端传的参数要用ctx.requst.body
如何注册egg-mongoose插件
我也是在网上找的资料,使用的是egg-mongoose,先注册插件,在config下的plugin里注册egg-mongoese,然后在同目录下的config.default.js下填写你的数据库配置信息,如下
// 连接服务器上的 mongodb 必须要设置密码才能连接(自己按照网上的方法设置数据库账号密码)
config.mongoose = {
url: 'mongodb://127.0.0.1:27017/pikachu666', // 端口号27017数据库名pikachu666
options: {
auth: { authSource: 'admin666' }, // 通过admin库进行登录认证
user: 'root', //账号名称
pass: '123456', // 你的密码
},
};
// 连接本地上的 mongodb 不需要设置密码也能连接(如果你本地没设置密码的话)
config.mongoose = {
url: 'mongodb://127.0.0.1:27017/pikachu666', // 端口号27017数据库名pikachu666
options: {
auth: { authSource: 'admin666' }, // 通过admin库进行登录认证
user: 'root', //账号名称
pass: '123456', // 你的密码
},
};
如何使用egg-mongoose
在使用之前,你需要在app/model 中定义你的schema,例如下面的代码
'use strict';
module.exports = app => {
const mongoose = app.mongoose; // 固定的
const Schema = mongoose.Schema; // 固定的
const UserSchema = new Schema({ // 这里就是你想要在数据库中定义的字段,及类型还有
id: { type: String },
name: { type: String },
});
return mongoose.model('Template', UserSchema, 'template'); // 这里的三个参数为 ('后面在Controller中操作数据库的模块','上面定义的Schema','你数据库中表的名字',)
};
然后在Controller中操作数据库,在下面举个简单的例子,我在这里写上几种简单的增删改查
'use strict';
const Controller = require('egg').Controller;
class ProjectController extends Controller {
async index() {
const { ctx } = this;
1.查询 (返回的都是数组)
// 查询 template 集合的所有数据
await ctx.model.Template.find();
//查询 template 集合中符合条件的数据
await ctx.model.Template.find({id:'xxx'});
//分页查询
this.ctx.model.Template.find({})
.skip(pageSize * (pageNum - 1))
.limit(parseInt(pageSize))
.sort({ stamp: -1 });
2.增加
ctx.model.User.create({id:'123',name:'张三'})
3.删除
ctx.model.User.deleteOne({id:'123'}),删除集合中首先找到的符合条件的数据
ctx.model.User.deleteMany({id:'123'}),删除集合中所有符合条件的数据
4.
ctx.model.User.updateOne({id:'123'}),更新集合中首先找到的符合条件的数据
ctx.model.User.updateMany({id:'123'},{name:'ls'}),更新集合中所有符合条件的数据
}
}
module.exports = ProjectController;
先分享下egg的初步学习的知识,下次分享egg如何实现token鉴权以及跨域,有什么不足,欢迎指出,谢谢