10_Node js 連線 MySQL 與 MongoDB
本篇文章講解了 Node.js 連線 MySQL 與 MongoDB,並實現基本的增刪改查功能。
這裡對安裝 MySQL 與 MongoDB 等軟體工具不做講解。
一、MySQL
1、設計表
首先通過視覺化工具進行表的設計,然後新增幾條測試資料:


2、安裝 Node.js 連線 MySQL 的包
npm i mysql -d 複製程式碼
3、連線 MySQL
MySQL.js
// 引入 mysql 包 const mysql = require('mysql'); // mysql 連線資訊 let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'test', port: 3306 }); // 開始連結 connection.connect(); // 查詢 info_test 表 connection.query('SELECT * FROM info_test', (error, results, fields) => { if (error) throw error; console.log(results); }); // 終止連線 connection.end(); 複製程式碼
執行 node MySQL.js,連線成功介面如下:

接下來就該實現增刪改查的功能了。
4、資料庫操作:增刪改查
4.1、增
add.js
const mysql = require('mysql'); let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'test', port: 3306 }); connection.connect(); // 設定 SQL 插入語句 let addSql = 'INSERT INTO info_test(id,name,age) VALUES(0,?,?)'; // 插入資料 let addSqlParams = ['zhao', '18']; // 連結 SQL 並實施語句 connection.query(addSql, addSqlParams, (error, response) => { if (error) { console.log("新增失敗!"); console.log(error); return; } else { console.log("新增成功!"); console.log(response); }; }); connection.end(); 複製程式碼
執行 node add.js

重新整理 Navicat,會看到新添加了一條資料。

4.2、刪
delete.js
const mysql = require('mysql'); let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'test', port: 3306 }); connection.connect(); // 設定 SQL 刪除語句 let delSql = 'DELETE FROM info_test where id=0'; connection.query(delSql, (error, response) => { if (error) { console.log("刪除失敗!"); console.log(error); return; } else { console.log("刪除成功!"); console.log(response); }; }); connection.end(); 複製程式碼
執行 node delete.js

重新整理 Navicat,會看到 id 為 0 的那條資料被刪除了。

4.3、改
update.js
const mysql = require('mysql'); let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'test', port: 3306 }); connection.connect(); // 設定 SQL 修改語句 let updateSql = 'UPDATE info_test SET name = ?,age = ? WHERE ID = ?'; // 要修改的資料 let updateSqlParams = ['Wang', '18', 1]; connection.query(updateSql, updateSqlParams, (error, response) => { if (error) { console.log("刪除失敗!"); console.log(error); return; } else { console.log("刪除成功!"); console.log(response); }; }); connection.end(); 複製程式碼
執行 node update.js

重新整理 Navicat,會看到 id 為 1 的那條資料被修改了。

4.4、查
read.js
const mysql = require('mysql'); let connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'test', port: 3306 }); connection.connect(); // 設定 SQL 修改語句 let readSql = 'SELECT * FROM info_test'; connection.query(readSql, (error, response) => { if (error) { console.log("查詢失敗!"); console.log(error); return; } else { console.log("查詢成功!"); console.log(response); }; }); connection.end(); 複製程式碼
執行 node read.js

二、MongoDB
1、安裝 mongodb 包
npm install mongodb --save

2、建立資料庫
要在 MongoDB 中建立一個數據庫,首先我們需要建立一個 MongoClient 物件,然後配置好指定的 URL 和 埠號。
如果資料庫不存在,MongoDB 將建立資料庫並建立連線,例如我們建立一個 test 資料庫:
MongoDB.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("資料庫已建立!"); db.close(); }); 複製程式碼

3、建立集合
我們可以使用 createCollection() 方法來建立集合:
修改 MongoDB.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function (err, db) { if (err) throw err; console.log('資料庫已建立'); var dbase = db.db("test"); dbase.createCollection('info_test', function (err, res) { if (err) throw err; console.log("建立集合 info_test!"); db.close(); }); }); 複製程式碼

如果你有 MongoDB 的視覺化工具,例如:Studio 3T,那麼你就可以看到剛剛建立的資料庫 test 和 集合(表) info_test 了。

4、資料庫操作:增刪改查
與 MySQL 不同的是 MongoDB 會自動建立資料庫和集合,所以使用前我們不需要手動去建立。
4.1、增
- 插入一條資料:insertOne();
- 插入多條資料:insertMany()。
以下例項我們連線資料庫 test 的 info_test 表,並插入一條資料,使用 insertOne():
add.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); var user = { name: "Liu", age: "24" }; dbo.collection("info_test").insertOne(user, function(err, res) { if (err) throw err; console.log("資料插入成功!"); db.close(); }); }); 複製程式碼


如果沒有安裝視覺化工具,我們也可以開啟 MongoDB 的客戶端檢視資料,如:

接下來我們使用 insertMany() 來插入多條資料。
add.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); var user = [{ name: "Zhao", age: "25" }, { name: "Sun", age: "18" }, { name: "Du", age: "23" }]; dbo.collection("info_test").insertMany(user, function(err, res) { if (err) throw err; console.log("插入" + res.insertedCount + "條資料成功!"); db.close(); }); }); 複製程式碼


4.2、刪
- 刪除一條資料:deleteOne();
- 刪除多條資料:deleteMany()。
將 name 為 "Sun" 的資料刪除:
delete.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 查詢條件 var whereStr = { "name": "Sun" }; dbo.collection("info_test").deleteOne(whereStr, function(err, res) { if (err) throw err; console.log("資料刪除成功!"); db.close(); }); }); 複製程式碼


將 age 為 23 的資料都刪除:
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 查詢條件 var whereStr = { age: "23" }; dbo.collection("info_test").deleteMany(whereStr, function(err, res) { if (err) throw err; console.log(res.result.n + " 條文件被刪除"); db.close(); }); }); 複製程式碼


4.3、改
- 修改一條資料:updateOne();
- 修改多條資料:updateMany()。
將 name 為 Liu 的 age 值改為 18:
update.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 查詢條件 var whereStr = { "name": "Liu" }; // 修改為: var updateStr = { $set: { "age": "18" } }; dbo.collection("info_test").updateOne(whereStr, updateStr, function(err, res) { if (err) throw err; console.log("資料修改成功!"); db.close(); }); }); 複製程式碼

修改多條資料,將 age 為 18 的資料 name 值改為 Wang:
update.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 查詢條件 var whereStr = { "age": "18" }; // 修改為: var updateStr = { $set: { "name": "Wang" } }; dbo.collection("info_test").updateMany(whereStr, updateStr, function(err, res) { if (err) throw err; console.log(res.result.nModified + "條資料修改成功!"); db.close(); }); }); 複製程式碼

4.4、查
可以使用 find() 來查詢資料, find() 可以返回匹配條件的所有資料,如果未指定條件,find() 返回集合中的所有資料。
read.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 查詢所有資料 dbo.collection("info_test").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); 複製程式碼

帶條件查詢,查詢所有 age 為 18 的資料:
update.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 查詢條件 var whereStr = { "age": "18" } dbo.collection("info_test").find(whereStr).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); 複製程式碼

4.5、排序
使用 sort() 方法,該方法接受一個引數,規定是升序(1)還是降序(-1)。
例如按照 age 值從小到大排序:
sort.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); // 排序條件 var mySort = { "age": 1 } dbo.collection("info_test").find().sort(mySort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); 複製程式碼

4.6、查詢分頁
如果要設定指定的返回條數可以使用 limit() 方法,該方法只接受一個引數,指定了返回的條數。
先來看一下 info_test 表中資料情況:

limit.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); dbo.collection("info_test").find().limit(2).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); 複製程式碼

如果要指定跳過的條數,可以使用 skip() 方法。
skip.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/test"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); dbo.collection("info_test").find().skip(2).limit(2).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); 複製程式碼

4.7、連線操作
mongoDB 不是一個關係型資料庫,但我們可以使用 $lookup 來實現左連線。
例如我們有兩個集合資料分別為:
集合1:orders
[ { _id: 1, product_id: 154, status: 1 } ] 複製程式碼
集合2:products
[ { _id: 154, name: '膝上型電腦' }, { _id: 155, name: '耳機' }, { _id: 156, name: '臺式電腦' } ] 複製程式碼
$lookup 實現左連線
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); dbo.collection('orders').aggregate([{ $lookup: { from: 'products', // 右集合 localField: 'product_id', // 左集合 join 欄位 foreignField: '_id', // 右集合 join 欄位 as: 'orderdetails' // 新生成欄位(型別array) } }]).toArray(function(err, res) { if (err) throw err; console.log(JSON.stringify(res)); db.close(); }); }); 複製程式碼
4.8、刪除集合
我們可以使用 drop() 方法來刪除集合:
drop.js
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("test"); dbo.collection("info_test").drop(function(err, delOK) { if (err) throw err; if (delOK) console.log("集合刪除成功!"); db.close(); }); }); 複製程式碼
