安装依赖
npm install egg-mongoose --save
package.json
"dependencies": {
"egg": "^3",
"egg-mongoose": "^3.3.1",
"egg-scripts": "^2"
},
配置信息
config\config.default.js
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {
security: {
csrf: {
enable: false,
},
},
mongoose: {
client: {
// 链接到本地的MongoDB,note是我本地数据库的名字
url: 'mongodb://127.0.0.1:27017/note',
options: {
// dbName: 'note',
useNewUrlParser: true,
},
},
},
};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1682063943419_2410';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
config\plugin.js
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
mongoose: {
enable: true,
package: 'egg-mongoose',
},
};
路由配置
app\router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/role', controller.role.index);
router.post('/roles', controller.rolePost.index);
};
定义model
app\model\role.js
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
// 连接数据库
const UserSchema = new Schema({
name: { type: String },
id: { type: String },
});
// 第一个参数模型
// 第二个参数 数据
// 第三个参数 操作的数据集合(表)
return mongoose.model('Role', UserSchema, 'user');
};
定义service
app\service\role.js
'use strict';
// app/service/user.js
const Service = require('egg').Service;
class RoleService extends Service {
async findRoleList() {
const { ctx } = this;
try {
// 説明ctx.model.Role中的Role為model目錄下文件的首字母大写
const results = await ctx.model.Role.find();
return results;
} catch (err) {
return JSON.stringify(err);
}
}
}
module.exports = RoleService;
定义controller
app\controller\role.js
'use strict';
const { Controller } = require('egg');
class RoleController extends Controller {
async index() {
const { ctx } = this;
const res = await ctx.service.role.findRoleList();
console.log('res', res);
ctx.body = res; // 返回值
}
}
module.exports = RoleController;
数据库查询的数据
数据库手动命令插入一条数据查询