我正在 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 客户端。
最佳答案
转发自https://jira.mongodb.org/browse/NODE-1868 :
弃用消息可能是因为 client.connect
被多次调用。总体而言,当前多次调用 client.connect
(从驱动程序 v3.1.13
开始)具有未定义的行为,因此不建议这样做。需要注意的是,一旦从 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
一次,然后在客户端对象上运行您的操作
* 请注意,客户端不是线程安全或 fork 安全的,因此它不能跨 fork 共享,并且与 Node 的 cluster
或 worker_threads
模块不兼容。
关于javascript - 为什么我会收到这个已弃用的警告?! MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54639778/