如何在 nodejs 3.0 mongo-client 中获取其他数据库实例?



我使用了mongo-nodejs 2.2并升级到3.0。升级后,我发现 Db 类中db()的方法不再存在(http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html)。此方法对于切换到不同的数据库实例非常有用。我想知道如何切换到具有最新版本的不同数据库。

好的,所以它消失了,它被记录为消失了,真正的信息是你应该改用Mongoclient.prototype.db

从 3.0 更改:

我们删除了以下 API 方法。

  • Db.prototype.authenticate
  • Db.prototype.logout
  • Db.prototype.open
  • 数据库原型.db

我们添加了以下 API 方法。

  • MongoClient.prototype.logout
  • MongoClient.prototype.isConnected
  • MongoClient.prototype.db

这里的基本教训是,无论您在哪里直接使用Db,都应该改用MongoClient实例。这是从第一个连接获得的:

const { MongoClient } = require('mongodb');
(async function() {
try {
const conn = await MongoClient.connect('mongodb://localhost');
let test = conn.db('test');
let admin = test.admin();
console.log(admin);
let another = conn.db('another');
console.log(another);
} catch(e) {
console.error(e);
} finally {
process.exit();
}
})()

返回如下输出:

Admin {
s:
{ db:
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
promiseLibrary: [Function: Promise] } }
Db {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ databaseName: 'another',
dbCache: {},
children: [],
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 25,
_maxListeners: Infinity,
clientInfo: [Object],
s: [Object] },
options:
{ readPreference: [Object],
promiseLibrary: [Function: Promise] },
logger: Logger { className: 'Db' },
bson: BSON {},
readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] }

有趣的是,admin()助手仍然存在于Db实例上,当然,这实际上只是旧db()的"预填充"选择。

底线是,将连接中的MongoClient实例用于所有将来的代码。

最新更新