node.js - 在 Node 中重用 MongoDB 连接

标签 node.js mongodb vows

这是我收到的错误:[错误:数据库对象已连接,无法多次调用 open]。我在这个誓言测试中有一个全局 mongo 对象。

mongo = new mongo.Db(config.api.apiTest, new mongo.Server('localhost', 27017, {}), {native_parser: off, safe: true})

当我第二次尝试打开它时,出现此错误。

因此,即使我第一次使用db.close(),它似乎也没有关闭。还有其他方法可以重用连接吗?

.addBatch(
  "Redis - ":
    "Standard account - ":
      topic: ->

        # .
        redisClient.del "#{ accountId }:900"

        mongo.open (error, db) =>
          secondDb = db.db config.api.accountTest

          secondDb.collection 'accounts', (error, accountsColl) =>
            accountsColl.update {'accountId': ObjectID(accountId)}, { "$unset": {'permission': ''}}, (error, records) =>
              console.log "Unset? " + records
              db.close()
          db.close()


        inventory = nock('http://inventory.honshuu.vgrnt:80')
            .get("/devices/?accountId=#{ accountId }&userId=#{ userId }")
            .reply(200, 'OK')

        httpRequest.get 'http://127.0.0.1:18091/inventory/devices/?token=testtoken', @callback
        return

      "Ratelimit is applied correctly":
        (error, response, body) ->
          accountLimit = response.headers['x-ratelimit-limit']
          assert.equal response.headers['x-ratelimit-remaining'], 240-1
          assert.equal response.headers['x-ratelimit-reset'], 900

    "account":
      topic: ->
        # Need to fetch permission in db.
        # redisClient.del "permission-#{ accountId }", (error, result) =>
        #   console.log "removes"
        #   console.log result

        inventory = nock('http://inventory.honshuu.vgrnt:80')
          .get("/devices/?accountId=#{ accountId }&userId=#{ userId }")
          .reply(200, 'OK')

        mongo.open (error, db) =>
          secondDb = db.db config.api.accountTest
          console.log secondDb

          secondDb.collection 'accounts', (error, accountsColl) =>
            accountsColl.update {'accountId': ObjectID(accountId)}, { 'permission': 1000}, (error, records) =>
              console.log "updated? " + records
              httpRequest.get 'http://127.0.0.1:18091/inventory/devices/?token=testtoken', @callback
              return

        return

      "account has more rate tokens":
        (error, response, body) ->
          console.log response
          console.log error
          # accountLimit = response.headers['x-ratelimit-limit']
          # assert.equal response.headers['x-ratelimit-remaining'], 1000-1
          # assert.equal response.headers['x-ratelimit-reset'], 900
          # assert.equal response.headers['x-ratelimit-limit'], 1000
)

最佳答案

就像 Node 中的大多数事物一样,db.close 是异步的并接受回调。您需要传递回调或 promise 它并返回 promise 。仅当您确定数据库连接已关闭时才应执行下一次连接调用,并且您只能通过处理回调来知道这一点。

db.close(function (err) {
  if (err) return console.error('OH NOES, AN ERROR:', err);
  console.log('SUCCESS!');
  // db is now closed, do whatevs
});

关于node.js - 在 Node 中重用 MongoDB 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30650424/

相关文章:

node.js - 使用 Vows 测试 Mongoose 模型

node.js - Azure Bot Framework 的在线代码编辑器 - 接收错误 : destructure property 'applicationID' of 'undefined' or 'null'

javascript - Socket.io 将两个客户端添加到房间

javascript - Node js套接字解释

java - 使用 Java 和 Spring 数据在 mongodb 中批量插入仅插入一个文档

javascript - 用 Mongoose 保存图像

php - SQL 到 MongoDB?

macos - 在 zsh 中安装 npm 后找不到命令

javascript - 以太坊中的简单代币系统

node.js - 我应该从 Vows 切换到 Mocha 吗?