Skip to content

Instantly share code, notes, and snippets.

@pasupulaphani
Last active May 1, 2024 20:37
Show Gist options
  • Save pasupulaphani/9463004 to your computer and use it in GitHub Desktop.
Save pasupulaphani/9463004 to your computer and use it in GitHub Desktop.
Mongoose connection best practices
var db = mongoose.connect('mongodb://localhost:27017/DB');
// In middleware
app.use(function (req, res, next) {
// action after response
var afterResponse = function() {
logger.info({req: req}, "End request");
// any other clean ups
mongoose.connection.close(function () {
console.log('Mongoose connection disconnected');
});
}
// hooks to execute after response
res.on('finish', afterResponse);
res.on('close', afterResponse);
// do more stuff
next();
}
var express = require('express');
var MongoStore = require('connect-mongo')(express);
app.use(express.session({
secret: settings.cookie_secret,
store: new MongoStore({
"db": "dbName",
"host": "localhost",
"port": "27017",
"collection": "mysessions",
"clear_interval": 3600,
"auto_reconnect": true
})
}));
new MongoStore({
db: mongoose.connection.db
})
new MongoStore({
mongoose_connection : mongoose.connections[0],
})
var mongoose = require('mongoose');
describe('My test', function() {
before(function(done) {
//Another possibility is to check if mongoose.connection.readyState equals 1
if (mongoose.connection.db) return done();
mongoose.connect('mongodb://localhost/puan_test', done);
});
});
// You can put one ‘after()’ statement above all else that will run when all tests are finished
after(function(done){
db.connection.db.dropDatabase(function(){
db.connection.close(function(){
done();
});
});
});
var db = mongoose.connect('mongodb://localhost:27017/DB');
Model.findOne({}, function () {
// do your stuff
// For any weird reason you want to close connection everytime
db.disconnect();
});
var mongoose = require('mongoose');
var express = require('express');
var config = require('./config/config');
var db_server = process.env.DB_ENV || 'primary';
mongoose.connection.on("connected", function(ref) {
console.log("Connected to " + db_server + " DB!");
var app = express();
// add your middleware set-up
// add your routes
port = process.env.port || 3000;
ip = process.env.ip;
app.listen(port, ip, function() {
console.log('listening on port ' + port);
});
});
// If the connection throws an error
mongoose.connection.on("error", function(err) {
console.error('Failed to connect to DB ' + db_server + ' on startup ', err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection to DB :' + db_server + ' disconnected');
});
var gracefulExit = function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection with DB :' + db_server + ' is disconnected through app termination');
process.exit(0);
});
}
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);
try {
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 1 };
mongoose.connect(config.getDBURL(db_server));
console.log("Trying to connect to DB " + db_server);
} catch (err) {
console.log("Sever initialization failed " , err.message);
}
mongoose.connect(config.db, {auto_reconnect: true, native_parser: true}, function(err) {
var MongoStore = require("connect-mongodb");
var app = express();
app.use(express.session({
cookie: {maxAge: 60000 * 20},
secret: "secret",
store: new MongoStore({db: mongoose.connection.db})
}));
});
@sudeepdk
Copy link

thanks alot

@smahi
Copy link

smahi commented Aug 1, 2016

Thank you much.

@colkito
Copy link

colkito commented Oct 7, 2016

great job! thanks

@ansarizafar
Copy link

Is it necessary to close connection after each request?

@EJMason
Copy link

EJMason commented Apr 12, 2017

In mocha_test.js, is db ever defined?

after(function(done){
  db.connection.db.dropDatabase(function(){
    db.connection.close(function(){
      done();
    });
  });
});

@rafalagunas
Copy link

nice, thanks!

@karunt
Copy link

karunt commented May 21, 2019

What's the benefit of initializing express within the mongoose.connection.on section? And when you include the express initialization, all middleware and routes related code inside the mongoose.connection.on section, how do you avoid the express app from crashing because other files might be referencing the variable "app" which is used here to initialize express?

@jsonberry
Copy link

According to the Mongoose FAQ:

Q. Should I create/destroy a new connection for each database operation?
A. No. Open your connection when your application starts up and leave it open until the application shuts down.

I'm still working on sussing out all the info out there, it looks like there are two camps.

@hantsy
Copy link

hantsy commented May 21, 2021

@jsonberry Which means the connection instance is shared for all requests?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment