安装依赖
yarn add egg-mongoose
注册插件
'use strict';

module.exports = {
mongoose: {
enable: true,
package: 'egg-mongoose',
}
};

据我的理解这注册什么名 再config文件里就叫什么

配置mongodb

config/config.default.js

/* eslint valid-jsdoc: "off" */

'use strict';

const options = {
host: "xxx.xx.xx.x",
port: "27017",
db_name: "xxx",
user: "xxx",
pass: "xxx",
};

const url = `mongodb://${options.user}:${options.pass}@${options.host}:${options.port}/${options.db_name}`;

/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};

// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1635295023359_9413';

// add your middleware config here
config.middleware = [];

// add your user config here
const userConfig = {
// myAppName: 'egg',
};

config.security = {
csrf: {
enable: false,
},
};

return {
...config,
...userConfig,
mongoose: {
url,
options: {
useUnifiedTopology: true
}
}
};
};

主要就原本的导出加一个mongoose属性

module.exports = appInfo => {
return {
...config,
...userConfig,
mongoose: {
url:"mongodb://xxxxxx",
options: {
useUnifiedTopology: true
}
}
};
}

使用

model 创建 表字段类型 很重要 没有注册字段controller中无法操作

再 ​​app/model​​​ 下 建文件操作一个表 如
​​​app/model/comment.js​

module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
content: { type: String },
type: { type: Number },
sender: { type: mongoose.Types.ObjectId },
thumbsUp: { type: Number }
});

return mongoose.model('Comment', CommentSchema, 'comment');
}

这样 使用时就有 ​​ctx.model[.modelName]​​​​app/controller/comment.js​

const Controller = require('egg').Controller;

class CommentController extends Controller {
async queryComment() {
const { ctx } = this;

const comments = await ctx.model.Comment.find();
console.log("comments:", comments);
ctx.body = { comments };
}
}
关闭csrf (不建议)

刚进行请求时会报错 关闭安全策略可以访问但是不安全 有条件的不要这么做
​​​config/config.default.js​

config.security = {
csrf: {
enable: false,
},
};