Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Feb 16, 2016

thanks alot

@smahi

This comment has been minimized.

Copy link

commented Aug 1, 2016

Thank you much.

@colcodev

This comment has been minimized.

Copy link

commented Oct 7, 2016

great job! thanks

@ansarizafar

This comment has been minimized.

Copy link

commented Feb 9, 2017

Is it necessary to close connection after each request?

@EJMason

This comment has been minimized.

Copy link

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();
    });
  });
});
@rafastaria

This comment has been minimized.

Copy link

commented Apr 1, 2019

nice, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.