与mongoose / node.js共享数据库连接参数的最佳方法

我正在使用Mongoose来pipe理Mongo数据库。 我的连接文件很简单:

var mongoose = require('mongoose') mongoose.connection.on("open", function(){ console.log("Connection opened to mongodb at %s", config.db.uri) }); console.log("Connecting to %s", config.db.uri) mongoose.connect(config.db.uri) global.mongoose = mongoose 

然后在我的app.js我只是

 require('./database) 

而“mongoose”variables在全球范围内可用。 我宁愿不使用全局variables(至less不是直接)。 有没有更好的方式通过节点(我使用express.js)通过单例模式或其他方法共享数据库连接variables?

我只是在我的app.js文件中执行以下操作:

 var mongoose = require('mongoose'); mongoose.connect('mongodb://address_to_host:port/db_name'); modelSchema = require('./models/yourmodelname').YourModelName; mongoose.model('YourModelName', modelSchema); // TODO: write the mongoose.model(...) command for any other models you have. 

在这一点上,任何需要访问该模型的文件都可以这样做:

 var mongoose = require('mongoose'); YourModelName = mongoose.model('YourModelName'); 

最后在您的模型中,您可以正常写入文件,然后将其导出到底部:

 module.exports.YourModelName = YourModelName; 

我不知道这是否是最好的解决scheme(大约2天前刚刚开始在出口模块中包装我的头),但它确实有效。 也许有人可以评论,如果这是一个好办法做到这一点。

如果你遵循commonjs出口

 exports.mongoose = mongoose 

让我们说你的模块名称是connection.js

你可以要求

  var mongoose = require('connection.js') 

你可以使用mongoose连接

我通常这样包装我的模型

 var MySchema = (function(){ //Other schema stuff //Public methods GetIdentifier = function() { return Id; }; GetSchema = function() { return UserSchema; }; return this; })(); if (typeof module !== 'undefined' && module.exports) { exports.Schema = MySchema; } 

而在我的主类,我做这个var schema = require('./schema.js').Schema; 并调用conn.model(schema.GetIdentifier(), schema.GetSchema()) ,当然在调用connect或createConnection之后。 这使我可以将模式插入标准的方法集。 这种泛化是很好的,因为在掌握了连接和error handling之后,您可以专注于您的模式。 我还使用插件扩展了模式,并允许我与其他模式共享插件。

我期待着看有没有更好的方法,但看不到一个好的模式,对于Mongo来说我还算是一个新手。

我希望这有帮助。