为什么我收到这个弃用的警告?! MongoDB的

问题描述 投票:0回答:2

我在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语句时(也就是说,当我进行SECOND连接时),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客户端。

javascript node.js mongodb
2个回答
4
投票

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模块不兼容。


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
});

Note

请务必查看MongoClient docs,你会发现许多可以指导你更好的好例子。

© www.soinside.com 2019 - 2024. All rights reserved.