创建项目
mkdir helloEjj
cd helloEjj
yarn create egg --type=simple
yarn install
yarn dev
连接mongodb
安装egg-xxx 插件后 在 plugin.js注册 挂载到app上 mongoose 的mode约定在model文件下 controller 下的ctx.model.modelName使用
yarn add egg-mongoose
config/plugin.js
module.exports = {
mongoose: {
enable: true,
package: 'egg-mongoose',
}
};
config/config.default.js 在原来的导出中加入 mongoose的配置
module.exports = appInfo => {
const options = {
host: "xxx.xxx.xx.xx",
port: "27017",
db_name: "xxx",
user: "xx",
pass: "xx",
};
const url = `mongodb://${options.user}:${options.pass}@${options.host}:${options.port}/${options.db_name}`;
return {
xxxxx,
mongoose: {
url
}
}
使用时需要按约定 来
创建model 目录 下面的文件名对应app/controller 下的文件名
model/comment.js
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const CommentSchema = new Schema({
content: { type: String },
type: { type: Number },
});
return mongoose.model('Comment', CommentSchema);
}
app/controller/comment.js
'use strict';
const Controller = require('egg').Controller;
class CommentController extends Controller {
async queryComment() {
const { ctx } = this;
console.log("Comment:", ctx.model.Comment.find({}))
ctx.body = 'createComment';
}
}
module.exports = CommentController;
参考
技术胖–Egg.js快速入门 egg-mongoose mongoose中文文档
|