gpt4 book ai didi

node.js - MongoClient.connect不执行回调函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:05 35 4
gpt4 key购买 nike

我对 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 creating connection 0 with options [{"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', message: 'creating connection 0 with options [{"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}]', className: 'Connection', pid: 9352, date: 1506430786041 }

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

我现在陷入困境,有人可以帮我解决这个问题吗,先谢谢了。

最佳答案

您正在 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();
});
});

关于node.js - MongoClient.connect不执行回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46427457/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com