为什么我会收到此已过时的警告?! MongoDB

时间:2019-02-11 21:57:12

标签: javascript node.js mongodb

我正在NodeJS中使用MongoDB,

    const { MongoClient, ObjectId } = require("mongodb");

const MONGO_URI = `mongodb://xxx:xxx@xxx/?authSource=xxx`; // prettier-ignore

class MongoLib {

  constructor() {
    this.client = new MongoClient(MONGO_URI, {
      useNewUrlParser: true,
    });
    this.dbName = DB_NAME;
  }

  connect() {
    return new Promise((resolve, reject) => {
      this.client.connect(error => {
        if (error) {
          reject(error);
        }
        resolve(this.client.db(this.dbName));
      });
    });
  }
  async getUser(collection, username) {
    return this.connect().then(db => {
      return db
        .collection(collection)
        .find({ username })
        .toArray();
    });
  }
}

let c = new MongoLib();

c.getUser("users", "pepito").then(result => console.log(result));
c.getUser("users", "pepito").then(result => console.log(result));

并且在执行最后一个c.getUser语句时(也就是说,当我进行第二次连接时),Mongodb输出以下警告:

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]

但是我没有使用任何不推荐使用的选项。有什么想法吗?


编辑

在注释中与 molank 进行了少量讨论之后,看来从同一服务器打开多个连接不是一个好习惯,因此警告可能就是这么想的(我认为很糟糕) )。因此,如果您遇到相同的问题,请保存连接而不是mongo客户端。

3 个答案:

答案 0 :(得分:1)

函数 .connect() 接受 3个参数,并定义为MongoClient.connect(url[, options], callback)。因此,您需要首先提供一个URL,然后提供选项,然后才提供回调。这是文档中的示例

MongoClient.connect("mongodb://localhost:27017/integration_tests", { native_parser: true }, function (err, db) {
    assert.equal(null, err);

    db.collection('mongoclient_test').update({ a: 1 }, { b: 1 }, { upsert: true }, function (err, result) {
        assert.equal(null, err);
        assert.equal(1, result);

        db.close();
    });
});

另一种可行的方法,因为您已经创建了MongoClient,而是使用 .open 。它仅接受回调,但是您可以从创建的mongoClient调用(this.client)进行调用。您可以这样使用它

this.client.open(function(err, mongoclient) {
    // Do stuff
});

注意

确保您查看了MongoClient docs,您会发现很多很好的示例,它们可能会更好地指导您。

答案 1 :(得分:1)

https://jira.mongodb.org/browse/NODE-1868转发:

弃用消息可能是因为多次调用client.connect。总体而言,当前(自驱动程序client.connect起,多次调用v3.1.13具有不确定的行为,因此不建议这样做。请务必注意,一旦connect返回的承诺解决后,客户端将保持连接状态,直到您致电client.close

const client = new MongoClient(...);

client.connect().then(() => {
  // client is now connected.
  return client.db('foo').collection('bar').insertOne({
}).then(() => {
  // client is still connected.

  return client.close();
}).then(() => {
  // client is no longer connected. attempting to use it will result in undefined behavior.
});

默认情况下,客户端与与其连接的每个服务器保持多个连接,并且可用于多个同时操作*。您应该可以一次运行client.connect,然后在客户端对象上运行您的操作

*请注意,客户端不是线程安全或派生安全的,因此不能在派生之间共享,并且它与节点的clusterworker_threads模块不兼容。

答案 2 :(得分:0)

poolSize 已弃用,请使用 maxPoolSize