【问题标题】:MongoClient.connect doesn't execute callback functionMongoClient.connect 不执行回调函数
【发布时间】:2018-03-07 17:40:39
【问题描述】:

我对 node.js 比较陌生。尝试使用 mocha 框架和 mongodb 驱动程序测试与 mongodb 的连接。

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-Connection:9352] 1506430786041 使用选项创建连接 0 [{"host":HOST,"port":PORT,"size":5,"keepAlive":true,"keepAliveInitialDelay":300000,"noDelay ":true,"connectionTimeout":30000,"socketTimeout":360000,"ssl":true,"ca":null,"crl":null,"cert":null,"rejectUnauthorized":false,"promoteLongs": true,"promoteValues":true,"promoteBuffers":false,"checkServerIdentity":true}] { type: 'debug', 消息:'使用选项创建连接 0 [{"host":HOST,"port":PORT,"size":5,"keepAlive":true,"keepAliveInitialDelay":300000,"noDelay":true,"connectionTimeout": 30000,"socketTimeout":360000,"ssl":true,"ca":null,"crl":null,"cert":null,"rejectUnauthorized":false,"promoteLongs":true,"promoteValues":true, "promoteBuffers":false,"checkServerIdentity":true}]', 类名:'连接', PID:9352, 日期:1506430786041 }

还检查了连接字符串是否正确,我可以通过另一个应用程序(在 SoapUI 中执行的 groovy 脚本)建立与它的连接。

我被困在这一点上,有人可以帮我解决这个问题,在此先感谢。

【问题讨论】:

    标签: node.js mongodb mocha.js


    【解决方案1】:

    您在来自 MongoClient.connect 的异步回调之外从 Mocha 调用 done()。所以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();
        });
    });
    

    【讨论】:

    • 不客气,如果有效,您可以将其标记为正确:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多