diff --git a/lib/Express.js b/lib/Express.js index 0d36e226..16d0fe5a 100644 --- a/lib/Express.js +++ b/lib/Express.js @@ -1,40 +1,43 @@ -var orm = require("./ORM"); -var _models = {}; -var _db = null; +var orm = require("./ORM"); + +var dbReady = null; module.exports = function (uri, opts) { + var _db = null; + var _models = {}; + opts = opts || {}; orm.connect(uri, function (err, db) { if (err) { if (typeof opts.error == "function") { opts.error(err); - } else { - throw err; } return; } - if (Array.isArray(_db)) { - _db.push(db); - } else if (_db !== null) { - _db = [ _db, db ]; - } else { - _db = db; - } + _db = db; if (typeof opts.define == "function") { - opts.define(db, _models); + opts.define(db, _models, function () { + if (Object.keys(_models).length > 0) { + _db = _models; + } + }); + } + if(typeof(dbReady) == 'function') { + dbReady(); } }); return function ORM(req, res, next) { - if (req.hasOwnProperty("models")) { + if(_db) { + req.db = _db; return next(); + } else { + dbReady = function dbReady () { + req.db = _db; + return next(); + } } - - req.models = _models; - req.db = _db; - - return next(); }; };