
- 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 - 概覽
什麼是 Node.js?
Node.js 是一個基於 Google Chrome 的 JavaScript 引擎(V8 引擎)構建的伺服器端平臺。Node.js 由 Ryan Dahl 於 2009 年開發,最新版本為 v0.10.36。根據其官方文件提供的定義,Node.js 是:
Node.js 是一個基於Chrome 的 JavaScript 執行時環境構建的平臺,用於輕鬆構建快速且可擴充套件的網路應用程式。Node.js 使用事件驅動、非阻塞 I/O 模型,使其輕量級且高效,非常適合跨分散式裝置執行的資料密集型即時應用程式。
Node.js 是一個開源的、跨平臺的執行時環境,用於開發伺服器端和網路應用程式。Node.js 應用程式使用 JavaScript 編寫,可以在 OS X、Microsoft Windows 和 Linux 上的 Node.js 執行時環境中執行。
Node.js 還提供了一個豐富的各種 JavaScript 模組庫,在很大程度上簡化了使用 Node.js 開發 Web 應用程式的過程。
Node.js = Runtime Environment + JavaScript Library
mongodb
mongodb 是 Node.js 驅動程式,用於連線 MongoDB 並對其執行資料庫操作。要安裝 mongodb,請執行以下 npm 命令。
npm install mongodb + mongodb@3.6.9 added 1 package from 1 contributor in 1.781s
建立/連線到資料庫
一旦例項化了 mongoClient,就可以使用其 connect() 方法獲取到資料庫連線。
// MongoDBClient const client = new MongoClient(url, { useUnifiedTopology: true }); // make a connection to the database client.connect(function(error) { if (error) throw error; console.log("Connected!"); // create or connect to database const db = client.db(database); // close the connection client.close(); });
如果資料庫不存在,則上述命令將建立它。
在後續章節中,我們將學習如何使用 Node 對 MongoDB 執行各種操作。
Node & MongoDB - 環境設定
安裝 MongoDB 資料庫
按照使用MongoDB - 環境提供的 MongoDB 安裝步驟進行操作。
安裝 Node
線上即時演示選項
您實際上不需要設定自己的環境來開始學習 Node.js。原因很簡單,我們已經在網上設定了 Node.js 環境,這樣您就可以線上執行所有可用的示例並透過實踐學習。隨意修改任何示例並使用不同的選項檢查結果。
使用下面示例程式碼框(在我們的網站上)右上角的即時演示選項嘗試以下示例:
/* Hello World! program in Node.js */ console.log("Hello World!");
在本教程中給出的大多數示例中,您會找到一個“嘗試一下”選項,因此只需使用它並享受您的學習過程。
本地環境設定
如果您仍然希望為 Node.js 設定環境,則需要在您的計算機上安裝以下兩個軟體:(a)文字編輯器和(b)Node.js 二進位制安裝程式。
文字編輯器
這將用於鍵入您的程式。一些編輯器的示例包括 Windows 記事本、OS Edit 命令、Brief、Epsilon、EMACS 和 vim 或 vi。
文字編輯器的名稱和版本在不同的作業系統上可能有所不同。例如,Notepad 將在 Windows 上使用,而 vim 或 vi 則可以在 Windows 以及 Linux 或 UNIX 上使用。
您使用編輯器建立的檔案稱為原始檔,其中包含程式原始碼。Node.js 程式的原始檔通常以“.js”副檔名命名。
在開始程式設計之前,請確保您已準備好一個文字編輯器,並且您有足夠的經驗來編寫計算機程式,將其儲存在檔案中,最後執行它。
Node.js 執行時環境
在原始檔中編寫的原始碼只是 JavaScript 程式碼。Node.js 直譯器將用於解釋和執行您的 JavaScript 程式碼。
Node.js 發行版作為 SunOS、Linux、Mac OS X 和 Windows 作業系統的二進位制安裝程式提供,適用於 32 位(386)和 64 位(amd64)x86 處理器架構。
以下部分指導您如何在各種作業系統上安裝 Node.js 二進位制發行版。
下載 Node.js 歸檔檔案
從Node.js 下載下載最新版本的 Node.js 可安裝歸檔檔案。在撰寫本教程時,以下版本在不同的作業系統上可用。
作業系統 | 歸檔檔名稱 |
---|---|
Windows | node-v12.16.1-x64.msi |
Linux | node-v12.16.1-linux-x86.tar.gz |
Mac | node-v12.16.1-darwin-x86.tar.gz |
SunOS | node-v12.16.1-sunos-x86.tar.gz |
在 UNIX/Linux/Mac OS X 和 SunOS 上安裝
根據您的作業系統架構,下載並將歸檔檔案 node-v12.16.1-osname.tar.gz 解壓縮到 /tmp,然後最終將解壓縮的檔案移動到 /usr/local/nodejs 目錄。例如
$ cd /tmp $ wget http://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.gz $ tar xvfz node-v12.16.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv node-v12.16.1-linux-x64/* /usr/local/nodejs
將 /usr/local/nodejs/bin 新增到 PATH 環境變數。
作業系統 | 輸出 |
---|---|
Linux | export PATH=$PATH:/usr/local/nodejs/bin |
Mac | export PATH=$PATH:/usr/local/nodejs/bin |
FreeBSD | export PATH=$PATH:/usr/local/nodejs/bin |
在 Windows 上安裝
使用 MSI 檔案並按照提示安裝 Node.js。預設情況下,安裝程式在 C:\Program Files\nodejs 中使用 Node.js 發行版。安裝程式應在 Windows 的 PATH 環境變數中設定 C:\Program Files\nodejs\bin 目錄。重新啟動任何開啟的命令提示符以使更改生效。
驗證安裝:執行檔案
在您的計算機(Windows 或 Linux)上建立一個名為main.js的 js 檔案,其中包含以下程式碼。
/* Hello, World! program in node.js */ console.log("Hello, World!")
現在使用 Node.js 直譯器執行 main.js 檔案以檢視結果:
$ node main.js
如果您的安裝一切正常,則應產生以下結果:
Hello, World!
mongodb
mongodb 是 Node.js 驅動程式,用於連線 MongoDB 並對其執行資料庫操作。要安裝 mongodb,請執行以下 npm 命令。
npm install mongodb + mongodb@3.6.9 added 1 package from 1 contributor in 1.781s
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!
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 }
Node & MongoDB - 刪除資料庫
要刪除資料庫,您可以使用database.drop()方法刪除選定的資料庫。
MongoClient.connect(url, function(error, client) { // Connect to the database const database = client.db('myDb'); // Drop the database database.dropDatabase(); });
示例
嘗試以下示例以刪除 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'); // Drop the database database.dropDatabase(); console.log("Database dropped!"); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! Database dropped!
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.
Node & MongoDB - 刪除集合
要刪除集合,您可以使用collection.drop()方法刪除集合。
MongoClient.connect(url, function(error, client) { // Connect to the database const database = client.db('myDb'); // drop the collection database.collection('sampleCollection').drop(function(error, status) { if (error) throw error; if (status) { console.log("Collection deleted"); } }); });
示例
嘗試以下示例以刪除 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.collection('sampleCollection').drop(function(error, status) { if (error) throw error; if (status) { console.log("Collection deleted."); } }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! Collection deleted.
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
Node & MongoDB - 插入文件
要將文件插入資料庫的集合中,您可以使用collection.insertOne()或collection.insertMany()方法插入一個或多個文件。
database.collection("sampleCollection").insertOne(firstDocument, function(error, res) { if (error) throw error; console.log("1 document inserted"); }); database.collection("sampleCollection").insertMany(documents, function(error, res) { if (error) throw error; console.log("Documents inserted: " + res.insertedCount); });
示例
嘗試以下示例以將文件插入 mongodb 集合中:
複製並貼上以下示例作為 mongodb_example.js:
const MongoClient = require('mongodb').MongoClient; // Prepare URL const url = "mongodb://:27017/"; const firstDocument = { First_Name : 'Mahesh', Last_Name : 'Parashar', Date_Of_Birth: '1990-08-21', e_mail: 'mahesh_parashar.123@gmail.com', phone: '9034343345' }; const documents = [{ First_Name : 'Radhika', Last_Name : 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' }, { First_Name : 'Rachel', Last_Name : 'Christopher', Date_Of_Birth: '1990-02-16', e_mail: 'rachel_christopher.123@gmail.com', phone: '9000054321' }, { First_Name : 'Fathima', Last_Name : 'Sheik', Date_Of_Birth: '1990-02-16', e_mail: 'fathima_sheik.123@gmail.com', phone: '9000012345' } ]; // 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'); database.collection("sampleCollection").insertOne(firstDocument, function(error, res) { if (error) throw error; console.log("1 document inserted"); }); database.collection("sampleCollection").insertMany(documents, function(error, res) { if (error) throw error; console.log("Documents inserted: " + res.insertedCount); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Documents inserted: 3 1 document inserted
Node & MongoDB - 選擇文件
要選擇集合的文件,您可以使用collection.findOne()或collection.find()方法選擇一個或多個文件。
database.collection("sampleCollection").findOne({}, function(error, result) { if (error) throw error; console.log(result); }); database.collection("sampleCollection").find({}).toArray(function(error, result) { if (error) throw error; console.log(result); });
示例
嘗試以下示例以選擇 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'); database.collection("sampleCollection").findOne({}, function(error, result) { if (error) throw error; console.log(result); }); database.collection("sampleCollection").find({}).toArray(function(error, result) { if (error) throw error; console.log(result); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: 'Radhika', Last_Name: 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' } [ { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: 'Radhika', Last_Name: 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' }, { _id: 60c4bbb40f8c3920a0e30fde, First_Name: 'Rachel', Last_Name: 'Christopher', Date_Of_Birth: '1990-02-16', e_mail: 'rachel_christopher.123@gmail.com', phone: '9000054321' }, { _id: 60c4bbb40f8c3920a0e30fdf, First_Name: 'Fathima', Last_Name: 'Sheik', Date_Of_Birth: '1990-02-16', e_mail: 'fathima_sheik.123@gmail.com', phone: '9000012345' }, { _id: 60c4bbb40f8c3920a0e30fdc, First_Name: 'Mahesh', Last_Name: 'Parashar', Date_Of_Birth: '1990-08-21', e_mail: 'mahesh_parashar.123@gmail.com', phone: '9034343345' } ]
Node & MongoDB - 更新文件
要更新集合的文件,您可以使用collection.updateOne()或collection.updateMany()方法更新一個或多個文件。
database.collection("sampleCollection").updateOne(query,updates, function(error, result) { if (error) throw error; console.log('Document Updated'); }); database.collection("sampleCollection").updateMany(query,updates, function(error, result) { if (error) throw error; console.log(result.result.nModified + " document(s) updated"); });
示例
嘗試以下示例以更新 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'); database.collection("sampleCollection").updateOne({First_Name:'Mahesh'}, { $set: { e_mail: 'maheshparashar@gmail.com' } }, function(error, result) { if (error) throw error; console.log('Document Updated.'); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! Document Updated.
Node & MongoDB - 刪除文件
要刪除集合的文件,您可以使用collection.deleteOne()或collection.deleteMany()方法刪除一個或多個文件。
database.collection("sampleCollection").deleteOne(query, function(error, result) { if (error) throw error; console.log('Document deleted.'); }); database.collection("sampleCollection").deleteMany(query, function(error, result) { if (error) throw error; console.log(result.result.n + " document(s) deleted."); });
示例
嘗試以下示例以刪除 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'); database.collection("sampleCollection").deleteOne({First_Name:'Mahesh'}, function(error, result) { if (error) throw error; console.log('Document Deleted.'); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! Document Deleted.
Node & MongoDB - 巢狀文件
要將巢狀文件插入資料庫的集合中,您可以使用collection.insertOne()或collection.insertMany()方法插入一個或多個文件。
database.collection("sampleCollection").insertOne(firstDocument, function(error, res) { if (error) throw error; console.log("1 document inserted"); }); database.collection("sampleCollection").insertMany(documents, function(error, res) { if (error) throw error; console.log("Documents inserted: " + res.insertedCount); });
示例
嘗試以下示例以將文件插入 mongodb 集合中:
複製並貼上以下示例作為 mongodb_example.js:
const MongoClient = require('mongodb').MongoClient; // Prepare URL const url = "mongodb://:27017/"; const firstPost = { title : 'MongoDB Overview', description : 'MongoDB is no SQL database', by: 'tutorials point', url: 'https://tutorialspoint.tw', comments: [{ user: 'user1', message: 'My First Comment', dateCreated: '20/2/2020', like: 0 }, { user: 'user2', message: 'My Second Comment', dateCreated: '20/2/2020', like: 0 }] }; // 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('posts'); database.collection("samplePost").insertOne(firstPost, function(error, res) { if (error) throw error; console.log("1 document inserted"); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected. 1 document inserted
Node & MongoDB - 限制記錄
要限制所選集合的文件,您可以使用collection.find().limit()方法選擇所需的文件。
database.collection("sampleCollection").find({}).limit(2).toArray(function(error, result) { if (error) throw error; console.log(result); });
示例
嘗試以下示例以選擇 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'); database.collection("sampleCollection").find({}).limit(2).toArray(function(error, result) { if (error) throw error; console.log(result); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! [ { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: 'Radhika', Last_Name: 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' }, { _id: 60c4bbb40f8c3920a0e30fde, First_Name: 'Rachel', Last_Name: 'Christopher', Date_Of_Birth: '1990-02-16', e_mail: 'rachel_christopher.123@gmail.com', phone: '9000054321' } ]
Node & MongoDB - 排序記錄
要對所選集合的文件進行排序,您可以使用collection.find().sort()方法對文件進行排序。
database.collection("sampleCollection").find({}).sort({First_Name: -1}).toArray(function(error, result) { if (error) throw error; console.log(result); });
示例
嘗試以下示例以選擇 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'); database.collection("sampleCollection").find({}).sort({First_Name: -1}).toArray(function(error, result) { if (error) throw error; console.log(result); }); // close the connection client.close(); });
輸出
使用 node 執行 mysql_example.js 指令碼並驗證輸出。
node mongodb_example.js Connected! [ { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: 'Radhika', Last_Name: 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' }, { _id: 60c4bbb40f8c3920a0e30fde, First_Name: 'Rachel', Last_Name: 'Christopher', Date_Of_Birth: '1990-02-16', e_mail: 'rachel_christopher.123@gmail.com', phone: '9000054321' }, { _id: 60c4bbb40f8c3920a0e30fdf, First_Name: 'Fathima', Last_Name: 'Sheik', Date_Of_Birth: '1990-02-16', e_mail: 'fathima_sheik.123@gmail.com', phone: '9000012345' } ]