与mongoose / node.js共享数据库连接参数的最佳方式 [英] Best way to share database connection param with mongoose/node.js
问题描述
我正在使用 Mongoose 来管理Mongo数据库。我的连接文件很简单:
I'm using Mongoose to manage a Mongo database. My connection file is quite simple:
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中我只是
Then in my app.js I just
require('./database)
和mongoose变量在全球可用。我不想使用全局变量(至少不直接)。有没有更好的方式通过单例模式或其他方法跨节点(我使用express.js)共享数据库连接变量?
and the "mongoose" variable is available globally. I'd prefer not to use globals (at least not directly). Is there a better way of sharing the database connection variable across node (I'm using express.js) via a singleton pattern or some other method?
推荐答案
我只在app.js文件中执行以下操作:
I just do the following in my app.js file:
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.
此时,需要访问该模型的任何文件都可以执行以下操作:
At this point any file that needs access to that model can do:
var mongoose = require('mongoose');
YourModelName = mongoose.model('YourModelName');
最后在您的模型中,您可以正确写入文件,然后将其导出到底部: / p>
And finally in your model, you can have the file written normally then export it at the bottom:
module.exports.YourModelName = YourModelName;
我不知道这是最好的最棒的解决方案(刚刚开始围绕导出模块约2天前),但它工作。也许有人可以评论,如果这是一个很好的方法。
I don't know if this the best most awesome solution (just started wrapping my head around exporting modules about 2 days ago) but it does work. Maybe someone can comment if this is a good way to do it.
这篇关于与mongoose / node.js共享数据库连接参数的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!