What is the best practice to connect/disconnect to a database? What is the best practice to connect/disconnect to a database? express express

What is the best practice to connect/disconnect to a database?


Its best practice to have your db connection in a separate module (db.js)

var mongoose = require('mongoose')mongoose.connect('mongodb://localhost/dbname', function(){    console.log('mongodb connected')})module.exports = mongoose

Each model should have a separate module that takes in the db connection (post.js)

var db = require('../db.js')var Post = db.model('Post', {    username: {type: String, required: true},    body: {type: String, required: true},    date: { type: Date, required: true, default: Date.now }  })module.exports = Post

Then whenever you need to use that data set just require it and make calls

var Post = require('/models/post')Post.save()Post.find()


This is an opinion based question I'd say. What I use for my app is

app.get('/', function (req, res) {res.sendfile('index.html');});mongoose.connect('mongodb://localhost:27017/my_db'); 

This way I create a connection once rather than on every HTTP request. Your way should work fine but it seems you will have to connect and disconnect the db to your app way too many times specially when the app is in development.


You want your connection to act like a singleton so as mentioned in the answer above it makes sense to do it outside of, and preferable before your routes:

var compression = require('compression');var express  = require('express');var app      = express();var port     = process.env.PORT || 8080;var cookieParser = require('cookie-parser');var bodyParser   = require('body-parser');var session      = require('express-session');...app.use(compression());// dbvar mongoose = require('mongoose');var configDB = require('./config/database.js');mongoose.connect(configDB.url); // connect to our database

config/database.js:

module.exports = {'url' : '@localhost:27017/dbname'};