【问题标题】:express app correct way to connect to mongo db?快速应用程序连接到 mongo db 的正确方法?
【发布时间】:2013-05-21 22:56:01
【问题描述】:

我有以下包含 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

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

这是正确的做法吗?

非常感谢任何建议。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

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

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

    您的db_connect_mongo 在成功情况下调用回调时违反了第一个参数为null 的节点约定。要纠正这个问题,不要使用callback(true, db) 来表示成功,使用callback(null, db)。除此之外,对于可以而且应该更简单的东西来说有点复杂,你所拥有的应该可以工作。

    【讨论】:

    • 它在我的情况下不起作用,因为如果我关闭 mongo,并尝试通过应用程序保存某些内容,mongoose 会记录正在保存的内容,但就是这样!我希望能够进行按摩以说“数据库未连接”...我如何更正节点约定以及如何使这更简单?谢谢
    • “你如何让这个更简单”有点超出了 stackoverflow 的格式,但是看看你有多少代码就像那个 90% 没用的巨型 switch 语句。 Mongoose 可能在 DB 关闭时对命令进行排队,这部分有用,部分烦人。目前还不清楚如何尽可能禁用它,但也许你可以进入mongoose.connection 对象。
    • 好的,但是关于 db_connect_mongo 的违规行为,你是什么意思?
    • 查看我编辑的答案。而不是callback(true, db),做callback(null, db)
    猜你喜欢
    • 2015-08-22
    • 2021-03-05
    • 2015-04-27
    • 2015-10-08
    • 2020-04-03
    • 2019-03-30
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多