为什么我会收到这个不建议使用的警告?!MongoDB

7

我正在使用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个回答

17

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

弃用信息可能是因为调用了多次client.connect。总的来说,当前(截至驱动程序v3.1.13)多次调用client.connect具有未定义行为,不建议这样做。需要注意的是,一旦从connect返回的promise解决,客户端将保持连接状态直到您调用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,然后在客户端对象上运行操作即可。请注意,客户端不支持线程安全或进程安全,因此不能在线程之间共享,也与node的clusterworker_threads模块不兼容。

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。它只需要一个回调函数,但您可以从您创建的mongoClientthis.client)中调用它。您可以像这样使用它:

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

注意

请务必查看MongoClient文档,您将会找到许多好的示例,这些示例可能会更好地指导您。


1
这并没有回答我的问题。open()被弃用了。我按照文档所说连接,但当我进行第二次连接时出现了这个问题。 - Antonio Gamiz Delgado
我现在没有明确地告诉它,但现在我会告诉它。 - Antonio Gamiz Delgado
答案仍然正确,“connect”仍然需要3个参数,而不仅仅是回调函数。 - molamk
1
嗯,你可以创建一个MongoClient(uri, options)的新实例(我们称之为db),然后调用db.connect(callback)。文档:http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html。实际上,如果我尝试使用open(),它会输出一个错误,告诉我open()不是一个函数。 - Antonio Gamiz Delgado
但是我需要多个连接 :( - Antonio Gamiz Delgado
显示剩余4条评论

0

poolSize已被弃用,请使用maxPoolSize


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接