
- Node 及 MongoDB 教程
- Node 及 MongoDB - 主頁
- Node 及 MongoDB - 概覽
- Node 及 MongoDB - 環境設定
- Node 及 MongoDB 示例
- Node 及 MongoDB - 連線資料庫
- Node 及 MongoDB - 顯示資料庫
- Node 及 MongoDB - 刪除資料庫
- Node 及 MongoDB - 建立集合
- Node 及 MongoDB - 刪除集合
- Node 及 MongoDB - 顯示集合
- Node 及 MongoDB - 插入文件
- Node 及 MongoDB - 選擇文件
- Node 及 MongoDB - 更新文件
- Node 及 MongoDB - 刪除文件
- Node 及 MongoDB - 嵌入式文件
- Node 及 MongoDB - 限制記錄
- Node 及 MongoDB - 排序記錄
- Node 及 MongoDB 有用的資源
- Node 及 MongoDB - 快速指南
- Node 及 MongoDB - 有用的資源
- Node 及 MongoDB - 討論
Node 及 MongoDB - 連線資料庫
Node mongodb 提供了 **mongoClient** 物件,該物件用於使用 connect() 方法連線資料庫連線。此函式採用多個引數,並提供 db 物件執行資料庫操作。
語法
// MongoDBClient const client = new MongoClient(url, { useUnifiedTopology: true }); // make a connection to the database client.connect();
你可以隨時使用另一個連線物件函式 **close()** 從 MongoDB 資料庫斷開連線。
語法
client.close()
示例
嘗試以下示例以連線到 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!"); // close the connection client.close(); });
輸出
使用 Node 執行 mysql_example.js 指令碼,並驗證輸出。
node mongodb_example.js Connected!
廣告