根据李成银大大的文章示例想做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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。