• Node.js Video Tutorials

Node.js - MongoDB 入門



在本章中,我們將學習如何在 Node.js 應用程式中使用 MongoDB 作為後端。Node.js 應用程式可以透過名為 mongodb 的 NPM 模組與 MongoDB 進行互動。MongoDB 是一個面向文件的 NoSQL 資料庫。它是一個開源的、分散式的、水平可擴充套件的無模式資料庫架構。由於 MongoDB 在內部使用類似 JSON 的格式(稱為 BSON)進行資料儲存和傳輸,因此它是 Node.js 的自然伴侶,Node.js 本身是一個 JavaScript 執行時,用於伺服器端處理。

安裝

MongoDB 伺服器軟體有兩種形式:社群版和企業版。MongoDB 社群版可在 Windows、Linux 和 MacOS 作業系統上使用,下載地址為 https://www.mongodb.com/try/download/community

Windows

下載最新版本的 MongoDB 安裝程式 (https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-7.0.4-signed.msi),並雙擊檔案啟動安裝嚮導。

MongoDB Server

選擇自定義安裝選項以指定合適的安裝資料夾。

Custom installation

取消選中“以服務方式安裝 MongoD”選項,並接受預設的資料和日誌目錄選項。

Directory Options

完成安裝嚮導中的其餘步驟。

建立一個目錄“d:\data\db”,並在以下命令列中將其指定為 dbpath 以啟動 MongoDB 伺服器:

"D:\mongodb7\mongod.exe" --dbpath="d:\data\db"

安裝程式還會指導您安裝 MongoDB Compass,這是一個用於與 MongoDB 伺服器互動的 GUI 客戶端。MongoDB 伺服器預設情況下在 27017 埠監聽傳入的連線請求。啟動 Compass 應用程式,並使用預設連線字串“mongodb://:27017”連線到伺服器。

MongoDB Compass

Ubuntu

要在 Ubuntu Linux 上安裝 MongoDB 伺服器,請發出以下命令重新載入本地包資料庫:

sudo apt-get update

現在您可以安裝最新穩定版本的 MongoDB 或特定版本的 MongoDB。

要安裝最新穩定版本,請發出以下命令:

sudo apt-get install -y mongodb-org

mongodb 驅動程式

現在我們需要從 NPM 倉庫安裝 mongodb 驅動程式模組,以便 Node.js 應用程式可以與 MongoDB 互動。

在新的資料夾中使用以下命令初始化一個新的 Node.js 應用程式:

D:\nodejs\mongoproj>npm init -y
Wrote to D:\nodejs\mongoproj\package.json:

{
   "name": "mongoproj",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
   },
   "keywords": [],
   "author": "",
   "license": "ISC"
}

使用以下命令從 NPM 倉庫安裝 mongodb 驅動程式模組:

D:\nodejs\mongoproj>npm install mongodb 

連線到 MongoDB

現在我們可以建立與 MongoDB 伺服器的連線。首先,使用 require() 語句從 mongodb 模組匯入 MongoClient 類。透過傳遞 MongoDB 伺服器 URL 呼叫其 connect() 方法。

const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myProject';

async function main() {
   // Use connect method to connect to the server
   await client.connect();
   console.log('Connected successfully to server');
   const db = client.db(dbName);
   const collection = db.collection('documents');

   // the following code examples can be pasted here...

   return 'done.';
}

main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());

假設上述指令碼儲存為 app.js,則從命令提示符執行應用程式:

PS D:\nodejs\mongoproj> node app.js
Connected successfully to server
done.
廣告