我正在使用Mongoose来管理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
然后在我的应用程序.js中,我只是
require('./database)
"猫鼬"变量在全球范围内可用。我宁愿不使用全局变量(至少不直接使用)。有没有更好的方法可以通过单例模式或其他方法在节点之间共享数据库连接变量(我使用的是express.js)?
我只是在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;
我不知道这是否是最好、最棒的解决方案(大约两天前我刚开始考虑导出模块),但它确实有效。也许有人可以评论这是否是一个好方法。
如果您遵循commonjs导出
exports.mongoose = mongoose
假设您的模块名称为connection.js
你可以要求
var mongoose = require('connection.js')
您可以使用猫鼬连接
我通常像这样包装我的模型
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之后。这允许我将模式插入到标准的方法集中。这种概括是很好的,因为在掌握了连接和错误处理之后,您可以专注于您的模式。我还使用插件扩展了模式,这允许我与其他模式共享插件。
我想看看是否有人做得更好,但找不到一个好的模式,我对Mongo还很陌生。
我希望这能有所帮助。