Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongodb - Best way to share database connection param with mongoose/node.js

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

Then in my app.js I just

require('./database)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...