我有这段代码来检查我的 MongoClient 是否已经连接:
connect(): Promise<null> {
const self = this;
if (this.client && this.client.isConnected()) {
return Promise.resolve(null);
}
return MongoClient.connect(this.uri).then(function (client) {
const db = client.db('local');
self.client = client;
self.coll = db.collection('oplog.rs');
return null;
});
}
问题是 isConnected 方法需要一些强制参数:
isConnected(name: string, options?: MongoClientCommonOption): boolean;
这里是信息:
http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#isConnected
所以我需要传递数据库名称以外的任何内容吗? 如果我不知道它可能连接到哪个数据库怎么办?
当我在运行时调试时,我只看到一个选项参数(只有一个参数,而不是两个):
(查看图片最右侧的 isConnected 方法)。
最佳答案
文档不正确。看着source code (第 395 行),唯一支持的参数是可选的 options
对象。
MongoClient.prototype.isConnected = function(options) {
options = options || {};
if (!this.topology) return false;
return this.topology.isConnected(options);
};
所以忽略文档,不要传递数据库名称。
关于node.js - 确定 MongoClient 实例是否已连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49332728/