Node 和 MongoDB - 建立集合



要建立集合,你可以使用 database.createCollection() 方法來建立集合。

MongoClient.connect(url, function(error, client) {
   // Connect to the database
   const database = client.db('myDb');  
   // Create the collection
   database.createCollection('sampleCollection');
});

示例

嘗試以下示例來建立 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'); 
   console.log("Collection created.");
   // close the connection
   client.close();
});

輸出

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

node mongodb_example.js
Connected!
Collection created.
廣告
© . All rights reserved.