Node 和 MongoDB - 顯示集合



要顯示資料庫的集合,可以使用 **database.listCollections()** 方法來獲取集合列表。

MongoClient.connect(url, function(error, client) {
   // Connect to the database
   const database = client.db('myDb');  
   // get the list of collections
   database.listCollections().toArray(function(err, collections) {
      collections.forEach(collection => console.log(collection.name));
   });
});

示例

嘗試以下示例來建立一個 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!");
   // Connect to the database
   const database = client.db('myDb');
   // Create the collection
   database.createCollection('sampleCollection');   
   database.listCollections().toArray(function(err, collections) {
      collections.forEach(collection => console.log(collection.name));
   });
   // close the connection
   client.close();
});

輸出

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

node mongodb_example.js
Connected!
sampleCollection
廣告