egg+mongodb 配置

2018-12-03  本文已影响50人  胡儒清

安装egg

启动

跨域设置
npm i egg-cors --save-dev
exports.cors = {
    enable: true,
    package: 'egg-cors',
};
  config.cors = {
      origin: '*', // 访问白名单,根据你自己的需要进行设置
      allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
  };

配置mogosse

  1. 文档 mongoose是nodeJS提供连接 mongodb的一个库,官网地址,学习文档

  2. 安装

npm install mongoose --save
  1. 测试连接是否成功,前提是你已经按照好了mongodb
const mongoose = require('mongoose');
mongoose.connect('mongodb://132.232.87.95:27017/test');
const con = mongoose.connection;
con.on('error', console.error.bind(console, '连接数据库失败'));
con.once('open', () => {
  console.log('连接成功');
});
  1. 配置
// config/plugin.js
exports.mongoose = {
    enable: true,
    package: 'egg-mongoose',
};
// config/config.default.js
config.mongoose = {
    url: 'mongodb://你的mongodb地址/apiExample',
    options: {},
};

  1. 编写一个添加用户接口
'use strict';

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

  const UserSchema = new Schema({
    userName: {
      type: String,
      unique: true,
      required: true,
    },
  });
  return mongoose.model('User', UserSchema);
};

'use strict';

const Service = require('egg').Service;
class UserService extends Service {
  // 更新用户信息
  async add() {
    const {
      ctx,
    } = this;
    const result = await ctx.model.User.create({
      userName: 'huruqing',
    });
    return result;
  }
}
module.exports = UserService;

'use strict';

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

class UserController extends Controller {
  async add() {
    this.ctx.body = this.ctx.service.user.add();
  }
}

module.exports = UserController;

router.get('/user/add')

mongoose常用操作

上一篇下一篇

猜你喜欢

热点阅读