ThinkJS2 mongoose 使用

根据李成银大大的文章示例想做ThinkJS的mongoose使用,发现有部分问题:
1、mongoose直接使用createConnection创建,每次Model创建实例导致重新创建新的连接,导致数据库连接无限上涨;
2、将connection缓存使用,导致mongoose的Model复写;

将这两个问题修复后,代码如下:
不过修改schema,自动编译不会mongoose的Model不会直接修复,需要重启服务生效;


"use strict";

let mongoose = require('mongoose');

let conn = null;
/**
 * model
 */
export default class extends think.base {
  /**
   * schema
   * @type {Object}
   */
  schema = {};
  /**
   * model instance
   * @type {[type]}
   */
  _model = null;

  /**
   * constructor
   * @param  {[type]} name   [description]
   * @param  {Object} config [description]
   * @return {[type]}        [description]
   */
  constructor(name, config = {}) {
    super();
    if (think.isObject(name)) {
      config = name;
      name = "";
    }
    this.name = name;
    this.config = think.parseConfig(config);
  }

  /**
   * 创建连接
   * @return {[type]} [description]
   */
  getConnection() {
    if (conn) {
      return conn;
    }
    let user = "";
    if (this.config.user) {
      user = this.config.user + ":" + this.config.password + "@";
    }
    let host = this.config.host || "127.0.0.1";
    let port = this.config.port || 27017;
    let str = `mongodb://${user}${host}:${port}/${this.config.database}`;
    conn = mongoose.createConnection(str);
    conn.on('connected', function (err) {
      if (err) {
        think.log('连接数据库失败:' + err);
      } else {
        think.log('连接数据库成功!');
      }
    });
    mongoose.Promise = Promise;
    return conn;
  }

  /**
   * 获取 Mongoose 里的 Model
   * @return {[type]} [description]
   */
  getModel() {
    if (!this._model) {
      let connection = this.getConnection();
      if(this.name in connection.models){
        this._model = connection.model(this.name);
      }else{
        this._model = connection.model(this.name, new mongoose.Schema(this.schema));
      }
    }
    return this._model;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值