表达app连接到mongo db的正确方法?

时间:2013-05-13 07:23:18

标签: node.js express mongoose

我有以下目录布局,其中包含node.js / express应用程序:

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

/src/config/index.coffee有mongo URL的详细信息,然后我将其导出为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

然后在/src/utils/dbconnect.coffee中,我有以下内容:

# 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

我假设一旦我启动应用程序,/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

连接保持打开状态,这样我就不必继续打开和关闭它了吗?

这是正确的做法吗?

任何建议都非常感激。

1 个答案:

答案 0 :(得分:0)

是的,一旦连接,连接将保持打开状态,直到明确断开连接或暂停一段时间。来自文档:

  

对于长期运行的应用程序,启用keepAlive通常是谨慎的。   没有它,经过一段时间后你可能会开始看到"连接   关闭"什么似乎没有理由的错误。如果是这样,看完之后   这个,您可以决定启用keepAlive:

在成功案例中调用回调时,您的db_connect_mongo违反了第一个参数为null的节点约定。要解决此问题,请不要使用callback(true, db)表示成功,请使用callback(null, db)。除此之外,对于可以而且应该更简单的事情来说有点复杂,你所拥有的应该是有效的。