Node 和 MongoDB - 顯示資料庫



若要顯示資料庫,可以使用 admin.listDatabases() 方法獲取所有資料庫的名稱,其中 admin 代表 admin 類。

MongoClient.connect(url, function(error, client) {
   // Use the admin database for the operation
   const adminDb = client.db('myDb').admin();
   // List all the available databases
   adminDb.listDatabases(function(err, dbs) {
      console.log(dbs);
   });
});

示例

嘗試以下示例連線到 MongoDB 伺服器 -

複製並貼上以下示例,命名為 mongodb_example.js -

const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://:27017/";
// make a connection to the database
MongoClient.connect(url, function(error, client) {
   if (error) throw error;
   console.log("Connected!");
   // Use the admin database for the operation
   const adminDb = client.db('myDb').admin();
   // List all the available databases
   adminDb.listDatabases(function(err, dbs) {
      console.log(dbs);
   });
   // close the connection
   client.close();
});

輸出

使用 node 執行 mysql_example.js 指令碼並驗證輸出。

node mongodb_example.js
Connected!
{
  databases: [
    { name: 'admin', sizeOnDisk: 40960, empty: false },
    { name: 'config', sizeOnDisk: 36864, empty: false },
    { name: 'local', sizeOnDisk: 73728, empty: false }
  ],
  totalSize: 151552,
  ok: 1
}
廣告