2017-09-26 60 views
1

我是比较新的Node.js的尝试使用mocha框架和mongodb驱动程序来测试与mongodb的连接。MongoClient.connect不执行回调函数

Node.js的版本 - 6.11.3

MongoDB的驱动程序版本 - 2.2.31

Mondodb版本 - 3.4.7

这是我的js文件:

var should = require("should"); 
var expect = require('chai').expect; 
var cfg = require('../config'); 
var uri = cfg.mongouri; 
var MongoClient = require('mongodb').MongoClient, Logger = 
require('mongodb').Logger; 

Logger.setLevel('debug'); 
describe("mongoconnection", function() { 

describe("fetch data", function() { 

    it("should fetch data from db", function (done) { 
     MongoClient.connect(uri,function(err, db) { 
       if (err) { 
        throw err; 
       } else { 
        console.log("successfully connected to the database"); 
       } 
       db.close(); 
      }); 
     done(); 
    }); 
}); 
}); 

然而中,代码

function(err, db) { 
      if (err) { 
       throw err; 
      } else { 
       console.log("successfully connected to the database"); 
      } 
      db.close(); 
     } 
的这一部分

从未得到执行,我无法建立连接,例如我没有得到控制台日志和例外。

调试信息:

[DEBUG-连接:9352] 1506430786041创建与项[{ “主机” 连接0:HOST, “端口”:PORT, “尺寸”:5 “的keepAlive”:真的, “keepAliveInitialDelay”:300000, “无延迟”:真实的, “connectionTimeout”:30000, “了socketTimeout”:360000, “SSL”:真实的, “CA”:空, “CRL”:空, “证书”:为空, “rejectUnauthorized”:假 “promoteLongs”:真 “promoteValues”:真 “promoteBuffers”:假 “checkServerIdentity”:真}] {类型: '调试', 消息:“创建与选择连接0 [{”举办 “:主机,” 口 “:PORT,” 大小 “:5” 的keepAlive “:真实的,” keepAliveInitialDelay “:300000,” 无延迟 “:真实的,” connectionTimeout “:30000,” 了socketTimeout “:360000,” SSL” :真, “CA”:空, “CRL”:空, “证书”:为空,“rejectUna uthorized“:false,”promoteLongs“:true,”promoteValues“:true,”promoteBuffers“:false,”checkServerIdentity“:true}]', className:'Connection', pid:9352, date:1506430786041}

也已经检查了连接字符串是正确的,我可以通过建立其他应用程序(在了SoapUI执行Groovy脚本)连接到它。

我停留在这一点上,有人可以帮助我,在此先感谢。

回答

2

要调用从摩卡done()MongoClient.connect异步回调之外。所以done()甚至可以连接到数据库之前被调用。

你的代码改成这样:

it("should fetch data from db", function (done) { 
    MongoClient.connect(uri,function(err, db) { 
      if (err) { 
       throw err; 
      } else { 
       console.log("successfully connected to the database"); 
      } 
      db.close(); 
      done(); 
    }); 
}); 
+0

感谢您的帮助! – penazik

+0

不客气,如果它工作,你可以标记它是正确的:) –