I have an app that does this kind of thing multiple times:
app.get('/', function(req, res){
MongoClient.connect(dbUrl, function(err, db){
//work with db data
});
});
But then I heard somewhere that it's better practice to connect to the database once, and use that connection on the whole thing. So does that mean something like this?:
MongoClient.connect(dbUrl, function(err, db){
app.get('/', function(req, res){
//do some stuff
});
app.get('/other', function(req, res){
//do some stuff
});
//
//more routers....
//
});
So which of these two methods would be considered better practice? And what makes it better? What is the difference? And is there a better way?
Connect once, watch for connection errors:
mongoose.connect(MONGO_URI);
var dbConnection = mongoose.connection;
dbConnection.on('error', console.error.bind(console, 'connection error...'));
dbConnection.once('open', function callback() { console.log('DB opened'); });
Use dbConnection
when you need to database access.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.