与 mongoose/node.js 共享数据库连接参数的最佳方式 [英] Best way to share database connection param with mongoose/node.js

查看:35
本文介绍了与 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');

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆