`

mongoose Mongoose类

 
阅读更多

在node.js中有个专门处理与数据库连接操作的模块mongodb,由于这个模块只是对mongodb的操作做了一层浅封装,用起来不是很好用。如是出现了一个开源的第三方模块mongoose,mongoose是建立在mongodb基础之上的一个比mongodb更好用的模块。

Mongoose是mongoose模块的入口类,它做了以下几件事情:

1.暴露内部模块,其实就是把它内部的很多模块集中起来,而Mongoose类作为外部访问它内部模块的统一接口。

2.创建连接并把所有的连接都放到一个connections集合里面。

3.定义模型并放到models集合里面,模型是mongoose操作数据库中的集合的最基本单元,注意这里是对模型的声明而不是定义。

4.声明并注册外部插件,存储的位置是plugins集合。

 

构造:

function Mongoose () {
  this.connections = [];
  this.plugins = [];
  this.models = {};
  this.modelSchemas = {};
  // default global options
  this.options = {
    pluralization: true
  };
  var conn = this.createConnection(); // default connection
  conn.models = this.models;
};

 构造注意是定义一些容器,然后就是创建一个默认的连接对象,这个连接对象就是我们经常用到的connect方法进行连接的时候用到的对象。由此可见连接对象是可以先创建再连接的。

 

创建连接:

Mongoose.prototype.createConnection = function () {
  var conn = new Connection(this);
  this.connections.push(conn);

  if (arguments.length) {
    if (rgxReplSet.test(arguments[0])) {
      conn.openSet.apply(conn, arguments);
    } else {
      conn.open.apply(conn, arguments);
    }
  }

  return conn;
};

Mongoose.prototype.connect = function () {
  var conn = this.connection;

  if (rgxReplSet.test(arguments[0])) {
    conn.openSet.apply(conn, arguments);
  } else {
    conn.open.apply(conn, arguments);
  }

  return this;
};

Mongoose.prototype.disconnect = function (fn) {
  var count = this.connections.length
    , error

  this.connections.forEach(function(conn){
    conn.close(function(err){
      if (error) return;

      if (err) {
        error = err;
        if (fn) return fn(err);
        throw err;
      }

      if (fn)
        --count || fn();
    });
  });
  return this;
};

 真正建立连接的行为是在Connection内部发生的,这里只是把参数传进去了。还有就是这里的disconnect是断开所有连接,要想断开单个连接直接用Connection对象就行了。要想把connections当做连接池估计还得自己做些处理。

 

暴露给外部的子模块:

Mongoose.prototype.Collection = Collection;
Mongoose.prototype.Connection = Connection;
Mongoose.prototype.version = pkg.version;
Mongoose.prototype.Mongoose = Mongoose;
Mongoose.prototype.Schema = Schema;
Mongoose.prototype.SchemaType = SchemaType;
Mongoose.prototype.SchemaTypes = Schema.Types;
Mongoose.prototype.VirtualType = VirtualType;
Mongoose.prototype.Types = Types;
Mongoose.prototype.Query = Query;
Mongoose.prototype.Promise = Promise;
Mongoose.prototype.Model = Model;
Mongoose.prototype.Document = Document;
Mongoose.prototype.Error = require('./error');
Mongoose.prototype.mongo = require('mongodb');
Mongoose.prototype.mquery = require('mquery');

 好多,以后慢慢看

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics