I have the following directory layout that contains a node.js / express application:
server.coffee
server.js
src
├── config
│ └── index.coffee
├── controllers
│ ├── index.coffee
│ └── user.coffee
├── index.coffee
├── models
│ └── user
│ └── user.coffee
├── routes.coffee
└── utils
├── dbconnect.coffee
views
├── 404.blade
├── 500.blade
├── index.blade
└── user
├── create.blade
the /src/config/index.coffee has details of the mongo URL which is i then export as DB_URL
#### Config file
# Sets application config parameters depending on `env` name
logger = require "../utils/logger"
logCategory = "Server config"
DB_HOST = "localhost"
DB_PORT = "27017"
DB_NAME = "zmgc"
DB_URL = null
DB_USER = null
DB_PASS = null
# Connecting to dexies database on mongodb
boundServices = if process.env.VCAP_SERVICES then JSON.parse(process.env.VCAP_SERVICES) else null
unless boundServices
if DB_USER and DB_PASS
DB_URL = "mongodb://#{DB_USER}:#{DB_PASS}@#{DB_HOST}:#{DB_PORT}/#{DB_NAME}"
else
DB_URL = "mongodb://#{DB_HOST}:#{DB_PORT}/#{DB_NAME}"
else
service_type = "mongodb-1.8"
credentials = boundServices["mongodb-1.8"][0]["credentials"]
DB_URL = "mongodb://" + credentials["username"] + ":" + credentials["password"] + "@" + credentials["hostname"] + ":" + credentials["port"] + "/" + credentials["db"]
#Set the current environment to true in the env object
exports.setEnvironment = (env) ->
logger.info "Set app environment: #{env}", logCategory
switch(env)
when "development"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.DB_URL = DB_URL
when "testing"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.DB_URL = DB_URL
when "staging"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.DB_URL = DB_URL
when "production"
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
exports.DB_URL = DB_URL
else
logger.info "Environment #{env} not found", logCategory
and then in /src/utils/dbconnect.coffee, i have the following:
# Connecting to database on mongodb
config = require "../config/index"
logger = require("./logger")
mongoose = require("mongoose")
mongoose.set "debug", true
logCategory = "DATABASE Connection"
db_connect_mongo = init: (callback) ->
self = this
mongo_options = db:
safe: true
db_url = config.DB_URL
mongoose.connect db_url, mongo_options
db = self.db_mongo = mongoose.connection
db.on "error", (error) ->
logger.error "ERROR connecting to: " + db_url, logCategory
callback error, null
db.on "connected", ->
logger.info "SUCCESSFULLY connected to: " + db_url, logCategory
callback true, db
db.on "disconnected", ->
logger.info "DISCONNECTED from the database: " + db_url, logCategory
# check and connect to Redis
exports = module.exports = db_connect_mongo
am i correct in assuming that once i start the application, /src/index.coffee :
express = require "express"
logger = require "./utils/logger"
# Initialize logger
logger.configure()
#### Application initialization
# Create app instance.
app = express()
# Define Port
app.port = process.env.PORT or process.env.VMC_APP_PORT or process.env.VCAP_APP_PORT or 3000
# Config module exports has `setEnvironment` function that sets app settings depending on environment.
config = require "./config"
logCategory = "Server"
app.configure "development", "testing", "staging", "production", ->
config.setEnvironment app.settings.env
# Database connection
dbconnection = require "./utils/dbconnect"
dbconnection.init (result) ->
if result
logger.info "Database initialized", logCategory
the connection stays open, so that i don't have to keep opening and closing this?
is this the correct approach to do this?
any advice much appreciated.
Yes, once you connect, the connection will stay open until explicitly disconnected or it goes idle for a while. From the docs:
For long running applictions it is often prudent to enable keepAlive. Without it, after some period of time you may start to see "connection closed" errors for what seems like no reason. If so, after reading this, you may decide to enable keepAlive:
Your db_connect_mongo violates the node convention that the first argument be null when invoking a callback in the success case. To correct this, don't use callback(true, db) to mean success, use callback(null, db). Other than that and being a bit complicated for something that can and should be much simpler, what you have should work.