node_使用mongo数据库

egg连接MongoDB数据库

  • $ npm install egg-mongoose --save
  • 开启插件config/plugin.js
mongoose: {
  enable: true,
  package: 'egg-mongoose'
}
  • mongo配置信息config.default.js
config.mongoose = {
  client: {
    url: 'mongodb:127.0.0.1/user', // user是数据库名称
    options: {},  // 其他配置项
  }
}
  • 设计模块app/model/UserInfo.js
'use strict';
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const userSchema = new Schema({
    // 设计文档字段
    username: { type: String },
    userpassword: { type: String },
  });
  // 第一个参数是跟 model 对应的集合( collection )名字的 单数 形式。 
  // Mongoose 会自动找到名称是 model 名字 复数 形式的 collection 
  // .model() 这个函数是对 schema 做了拷贝(生成了 model)。 
  // 要确保在调用 .model() 之前把所有需要的东西都加进 schema 里了
  // 相当于sql的设计表的字段
  // 第三个参数就是集合(数据表)的名字,如果省略mongoose会自动找到UserInfos
  return mongoose.model('UserInfo', userSchema, 'userInfo');
};
  • app/router.js
router.post('mongo', controller.mongo.tools)
  • app/controller/mongo.js
  'use strict';
  const Controller = require('egg').Controller;
  class MongoController extends Controller {
    async tools() {
      // 假设请求的参数为{username: 'jack', userpassword: '123456'}
      const query = this.ctx.request.body; 
      const result = await this.ctx.service.mongo.tools(query);
      this.ctx.response.body = result;
    }
  }
  module.exports = MongoController;

  • app/service/mongo.js
'use strict';

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

class MongoService extends Service {
  async tools(query) {
    model:     // 在设计模块时创建文件夹的名字
    UserInfo:  // 在设计模块时创建的js文件的名字
    // 插入多条文档
    const result = await this.ctx.model.UserInfo.insertMany(query);
    const result = await this.ctx.model.UserInfo(query); // 插入一条
    // 删除一条文档
    const result = await this.ctx.model.UserInfo.updateOne(query)
    
    // 修改一条文档
    const result = await this.ctx.model.UserInfo.updateOne(query, { username: query.username + 'hahah', userpassword: query.userpassword + 'hahah' });
    // 查询满足条件所有文档
    const result = await this.ctx.model.UserInfo.find(query);
    return result;
  }
}
module.exports = MongoService;

更多配置信息,查看mongoose中文网

猜你喜欢

转载自www.cnblogs.com/JunLan/p/12683395.html