在同一个MongoDB上两次调用connect失败

时间:2019-02-04 23:11:52

标签: node.js mongodb serverless

我遇到了一个问题,我有一个连接到数据库的NodeJS函数(在无服务器脱机状态下运行)。当我尝试进行一次连接时,此方法非常有效,但是当我尝试调用两次连接时,它会失败。我在调用connect之前正在检查连接,以便不进行冗余连接调用,但是不知何故,我收到了两个最终以mongoClient.connect()方法结束的调用,第二个调用将失败,并显示以下错误:

the options [servers] is not supported
the options [caseTranslate] is not supported
the options [username] is not supported
the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,keepAliveInitialDelay,connectTimeoutMS,family,socketTimeoutMS,reconnectTries,reconnectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bufferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,promoteValues,promoteBuffers,promoteLongs,domainsEnabled,checkServerIdentity,validateOptions,appname,auth,user,password,authMechanism,compression,fsync,readPreferenceTags,numberOfRetries,auto_reconnect,minSize,monitorCommands,retryWrites,useNewUrlParser]
the options [dbName] is not supported

我的代码相对简单:

public connect(): Promise < boolean > {
  return new Promise < boolean > (async(resolve, _reject) => {
    if (this._database !== null && this._mongoClient && this._mongoClient.isConnected()) {
      return resolve(true);
    }

    if (this._mongoClient === null) {
      this._mongoClient = new MongoClient(this._hostURL(), {
        useNewUrlParser: true,
      });
    }

    try {
      await this._mongoClient.connect();
    } catch (error) {
      process.stdout.write(error);
      _reject(error);
    }

    if (this._mongoClient.isConnected()) {
      this._database = this._mongoClient.db(this._hostDatabase);
      return resolve(true);
    } else {
      return resolve(false);
    }
  });
}

通过将其组合为一个promise并等待该promise两次调用此方法将失败。

我通过检查是否已经在连接过程中,然后稍等片刻,再次进行测试,直到退出连接过程为止,以此解决了问题,但这不是正确的方法解决这个问题。

任何建议都值得赞赏。

0 个答案:

没有答案