Udemy 的開發網頁線上課程學習筆記做個重點整理分享^^
SQL
MySQL 架構去查詢的語言
有一個龐大的數據 資料很多 我們人要從這個數據庫 提領我要的資料 給他指令
熱門常見的一種
What is DBMS? (什麼是數據庫管理系統?)
Stands for database management system (代表數據庫管理系統)
it helps us manage our database (它幫助我們管理我們的數據庫)
C.R.U.D 數據庫最基本能做的事情
Create 創造
Read 讀取
Update 更新
Delete 刪除
MySQL 屬於 SQL
MongoDB 屬於 NoSQL
大型資料都是用數據庫來解決 Relational database (有關係的數據庫)
KEY
Primary Key 他定義每一格的獨特性 可以確保說找到一筆唯一的資料 例公司名 找到他的名稱就可以找到很多相關資料
Foreign Key 跟上面有點類似 不過是牽到以外的
Natural Key 當使用者在輸入一些資料 你會問他身分證字號 全台灣都是不一樣 你把身分證字號當作表格的 Primary Key
在數據庫外部是有意義的
Surrogate Key (代理的) 當使用者在輸入一些資料 你會問他身分證字號 全台灣都是不一樣 你把身分證字號當作表格的 Primary Key
在數據庫外部是沒有意義的
Composite Key (組成.合成)
只有 Primary Key 合併後 才能做使用 有些數字可能會重複 所以不可能做使用 要合併名字
SQL 資料類型
常用類型
寫 Comment 方式 --
例: 1. -- SQL data types
2.INT (整數)
3.DECIMAL(p, s) (處理數字 例:3.14 p 代表全部 3 s 代表小數點後面幾個數 2)
4.VARCHAR(M) (後面一樣要設定長度 字串的意思 假設 M 設定 20 的話 最多只能有20個字)
5.DATE (格式就是 前面是 年分月份日 'YYYY-MM-DD')
假設有一個表格有 Employee ID Name Age Salary Supervisor DepartmentID
第一行
create table employees(
employeeID int PRIMARY key AUTO_INCREMENT,
employeeName varchar(25) NOT NULL,
age int,
salary int DEFAULT(1500),
supervisor int,
department int
);
DROP TABLE employees;--DROP掉就不復存在已run的資料 之後就可以把這行刪掉
DESCRIBE employees;--可以看這整個table 的資料
先打入以上讓他跑 run
再來在表單裡面加入資料 要一個個添加沒辦法一次
INSERT INTO employees VALUES(100, "Josh Donaldson", 35, 3500, null, 1);
INSERT INTO employees(employeeName, age, salary, supervisor, department) VALUES("Mike Napoly", 40, 2400, 100, 1);
INSERT INTO employees VALUES(102, "Cody Allen", 37, 2400, 100, 2);
INSERT INTO employees VALUES(103, "Nolan Ryan", 34, 1500, 101, 1);
INSERT INTO employees VALUES(104, "Jason Heyward", 33, 1500, 102, 2);
INSERT INTO employees VALUES(105, "Fred Johnson", 30, 1500, 101, 1);
INSERT INTO employees VALUES(106, "Zach Britton", 29, 1500, 101, 1);
INSERT INTO employees VALUES(108, "Oliver Perez", 30, 1500, 102, 2);
DESCRIBE employees; -- constraints 限制 看到這個就要特別做設定 這個觀看資料而已可以不打
把上面的資料打完 再跑一次
再把它移除跑下面這個程式碼
SELECT * FROM employees; -- 可以 run 出前面設定進去的資料
-- 可以把前面的108改成107 employeeID
UPDATE employees SET employeeID = 107 WHERE employeeID = 108;
-- 可以把前面的1500改成1800 salary
UPDATE employees SET salary = 1800 WHERE salary = 1500;
-- 刪除資料庫資料
DELETE FROM employees WHERE employeeID = 107;
(以下兩種方式較危險)
-- 會刪除所有 employeeID 裡面會為空 表格還會再
DELETE FROM employees;
-- 會刪除所有 employeeID 裡面會為空 表格刪除
DROP TABLE employees;
-- query 查詢
-- 選取所有的欄
SELECT *
FROM employees;
-- 根據年齡做排列
CRDER BY age; --由小到大
CRDER BY age DESC, salary; --年齡由大到小再根據薪水做排列
LIMIT 3; -- 回傳前面三行回來 也就可以找到前三老的人
-----------------
-- query 查詢更好的方式 找薪水大於 2000的
SELECT *
FROM employees;
WHERE salary >= 2000;
-- 在二號部門工作有誰
WHERE department = 2;
-- 找薪水大於 2000的 在二號部門工作有誰
WHERE department = 2 AND salary >= 2000;
-- 也可以就是不要找部門 2 的 就顯示除了二來其他的
WHERE department != 2;
-----------------
--查詢 employeeID employeeName
SELECT employeeID, employeeName
FROM employees;
MongoDB CRUD
這個服務開過之後 就不用移到 C:\Program Files\MongoDB\Server\4.4\bin 再移動開一次了 直接在桌面可以使用
打上 指令碼 mongo 即可使用
Mongo DB CRUD 同時也是 js 的 shell
移到輸入 cd C:\Program Files\MongoDB\Server\4.4\bin
到網站可以找使用方式 https://www.mongodb.com/docs/manual/crud/
到 MongoDB CRUD Operations 裡面找資訊 再到 insert Documents(新增物件) 裡面看
請下載 4.2.22版
之後環境建置
1. Insertion
2. Find
3.Update
4.Delete
下載 完之後 打開命令提示指令
請先到資料夾之後打入指令 mongo
輸入指令
把資料夾檔案路徑 用命令提示指令移到那個位置 之後輸入指令 mongo
啟動 mongo
指令打 db 可以只在哪個db裡面
打 show dbs 可以知道檔案幾個這樣
想用新的檔案
指令 use exampleDB
再檢查一下指令 show collections(在mongoDB裡面跟SQL 的 table 一樣)
然後再 這個 use exampleDB 沒有任何東西 再做一個 students
新增東西 在裡面再創建第二個物件
指令打 db.students.inserOne({name: "Wilson Ren", age: 22, major: "Computer Scicnce", scholarship: {merit: 300, other: 1500}})
在按下 Enter 如果在下面看到 "acknowledged" : true 就代表新增進去了
怎樣確定已經進去了咧 打指令
db.students.find() 裡面就找的到這個物件了
第二個可以用的指令碼 在一個資料可以放很多物件的指令 在裡面要放入 串列的物件
db.students.inserMany({name: "Mike Huang", age: 23, major: "Chemistry", scholarship: {merit: 4500, other: 3000, {name: "John Lee", age: 21, major: "EE", scholarship: {merit: 0, other: 5000}}})
再來第三個可以用的指令碼 他是前兩項的綜合體 可以直接使用
db.students.insert({name: "Jay", age: 25, major: "Computer", scholarship: {merit: 0, other: 0}})
就會顯示 WriteResult({"nlnserted": 1 }) 代表已經方一個物件在裡面
總結 建議用前面兩項 資訊會比較多^^
再來就是可以找到所有資料的指令
db.students.find({}) 就可以找到上方所有的檔案
然後可以搜尋到想要的物件 假如說 Wilson Ren 就只會回傳一個物件 如果有重複的物件 代表不會只回傳一個物件而已
db.students.find({name: "Wilson Ren"})
再來說一下 update 程式碼作用
db.students.updateOne({name: "Wilson Ren"}, {$set: {name: "Wilson Wu", age: 25}, $currentDate: {lastModified: true}})
出現 {"acknowledged": true, "matchedCount": 1, "modifedCount: 1"} 代表修改成功 Wilson Ren 改成
Wilson Wu 跟 25 歲 有很多個 Wilson Ren 他只會把第一個改成 Wilson Wu
自來另一個指令 他會把所有要改的全部改掉
db.students.updateMany({major: "Chemistry"}, {$set: {major: "Chem}})
再來出現 {"acknowledged": true, "matchedCount": 2, "modifedCount" : 2} 修改成功 matchedCount等於找到幾個物件 modifedCount 等於修改了兩個 等於全部的都被改掉
再來看 Delete 刪除物件
db.students.deleteOne({major: "Chem"}) 就可以刪除 但是只刪除 頭一個
刪除全部的
db.students.deleteMany({major: "Chem"})
再來可以用指令
db.students.find() 看一下
再來他要看如何找拿到他的獎學金是 2500元 語法很重要 可以上網頁看一下
db.students.find({"scholarship.merit" : 2500})
再來有多少人的獎學金是大於 1500 元
db.students.find({"scholarship.merit" : {$gt: 1500}})
然後我想在上面的資料 找到我的主修
db.students.find({major: {$in: ["EE", "Chem"]}})
MongoDB 要啟動服務 在下載檔案裏面設資料夾
接下來會使用 MongoDB 儲存 Register info.
註:
通常node.js會搭配MongoDB,因為MongoDB是使用javascript為腳本開發的,資料使用JSON格式儲存,這代表 MongoDB & Node.js 之間不需要額外的資料轉換就可以做資料交換。
下載MongoDB後安裝
MongoDB官網
安裝完畢後,到安裝路徑下準備mongodb資料和log儲存路徑
bin 資料夾內包含 Mongodb 的啟動相關程式
在bin同一層建立 data 資料夾、log資料夾
data內建立db資料夾
------------
用系統管理員權限打開cmd
輸入以下指令啟動MongoDB Service
(如果出現NET 2185存取被拒,表示沒有用系統管理員權限啟動服務)
# 啟動服務
net start MongoDB
Mongoose
SQL 1. PopSQL - mySQL Server
2. create table ------ datatype, name.....
----------------------------
Mongoose 的連結包 1.https://mongoosejs.com/docs/schematypes.html
2.https://mongoosejs.com/docs/validation.html
再命令提示 輸入 npm init 再把以下下載
install express nodemon ejs mongoose
連結到 mongoose 到他的網站 https://mongoosejs.com/
程式代碼填入 then 成功 catch 失敗
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// 出現 Connected to MongoDB 代表成功連上
//-------------
Mongoose 1.app.js - mongoDB 用法
Mondel and Schema
Schema會定義所有物件形狀長什麼樣子
Mondel就像在SQL裡面的 table
// define a schema (定義)
const studentSchema = new mongoose.Schema({
name: String,
age: Number,
major: String,
scholarship: {
merit: Number,
other: Number,
},
});
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 找到檔案的方法 下面的 Jon 要註解掉 object 和 save 兩個 只會找到唯一一筆而已
Student.find({}).then((data) => {
console.log(data);
});
// ---------------
// 1.找到檔案方式 跟以上分開喔 可以直接找名字 他是一個物件
Student.findOne({ name: "Jay Wu" }).then((data) => {
console.log(data);
});
// -------------------
// 依樣下面註解 但是上面的 find 也要註解(分開使用) 來學 update
// 1.update
// update 更改名字的意思 把前面原本的 改成後面2的 再來用以下的 find 尋找是否更改成功
Student.updateOne({ name: "Ku" }, { name: "Carl Renson" }).then((meg) => {
console.log(meg);
});
// ------------------
// update 第二種方式 改全部的
Student.updateMany({ major: "EE" }, { major: "Electrical Engineering" }).then(
(meg) => {
console.log(meg);
}
);
// find 以上要註解掉 用以上這邊要註解掉
// Student.find().then((data) => {
// console.log(data);
// });
//跟以上要分開唷
//----------
// 第三種方式
// findOneAndUpdate 會出現被更改過的資料 new 的用意 就不用再 find 搜尋
Student.findOneAndUpdate(
{ name: "Jay Wu" },
{ name: "Jay Ren" },
{ new: true }
).then((meg) => {
console.log(meg);
});
// -------------
//-------------------
// find 以上要註解掉 用以上這邊要註解掉
// Student.find().then((data) => {
// console.log(data);
// });
// ----------------------
//---------------------
// find 其他的用法 會找到誰超過或等於 1500元 $gte 用法
Student.find({ "scholarship.merit": { $gte: 1500 } }).then((data) => {
console.log(data);
});
// ----------------------
//-------------------
// 單獨使用 上面用不到可刪除唷 delete 刪除方式 如果符合大於 2800 我們就把它移除 要使用以下尋找要註解掉
Student.deleteOne({ "scholarship.merit": { $gte: 2800 } }).then((meg) => {
console.log(meg);
});
//---------------------
// find 要運用 find 以上一樣要註解掉 在搜尋
// Student.find().then((data) => {
// console.log(data);
// });
//-----------------------
// ----------------------
// 第二種方式 findOneAndDelete
// findOneAndDelete 刪除方式 可顯示刪除更改的檔案是什麼 就不用用 find 在尋找一次 如果符合大於 2800 我們就把它移除 要使用以下尋找要註解掉
Student.findOneAndDelete({ "scholarship.merit": { $gte: 2500 } }).then(
(meg) => {
console.log(meg);
}
);
// ----------------------
// create an object
const Jon = new Student({
name: "Jon Renson",
age: 25,
major: "EE",
scholarship: { merit: 2500, other: 1300 },
});
// save Jon to DB 我們要把這個 Jon 放進我們的 database 裡面
Jon.save()
.then(() => {
console.log("Jon has been saved into DB.");
})
.catch((e) => {
console.log("error has happened.");
console.log(e);
});
// -------------------
//-----------------------
/////////////////////
// 跟以上全部分開 定義第二種 Schema
///////////////////////
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true, // 就是一定要設定他的名字
},
age: {
type: Number,
required: true,
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
},
other: {
type: Number,
default: 0,
},
},
});
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 來看一下運用上面的定義會發生什麼
const newStudent = new Student({
name: "Nelson Cruz",
age: 18,
scholarship: { merit: "1500", other: "2000" }, // 會把 字串換成數字 運用以上會自動轉換
isMarried: true, // 沒有看到這個 是因為它的定義沒有在裡面
});
// 把它存進來
// newStudent
// .save()
// .then(() => {
// console.log("Data has been saved.");
// })
// .catch((e) => {
// console.log("error has happened.");
// console.log(e);
// });
// find 先把它註解掉 以上的物件 save 先註解掉 在執行下面的 find 查看長怎樣
Student.find().then((data) => {
console.log(data);
});
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
// ---------------------------
// ---------------------------
// // 跟以上全部分開 定義第三種 Schema
// --------------------------
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 來看一下運用上面的定義會發生什麼
const newStudent = new Student({
name: "Luke Willington",
age: 27,
major: "Law", // 設定沒有跟上面一樣就會報錯
scholarship: { merit: "1500", other: "2000" }, // 會把 字串換成數字 運用以上會自動轉換
isMarried: true, // 沒有看到這個 是因為它的定義沒有在裡面
});
// 把它存進來
newStudent
.save()
.then(() => {
console.log("Data has been saved.");
})
.catch((e) => {
console.log("error has happened.");
console.log(e);
});
// find 先把它註解掉 以上的物件 save 先註解掉 在執行下面的 find 查看長怎樣
// Student.find().then((data) => {
// console.log(data);
// });
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
//------------------------------------
//
//------------------------------------
// 第四種的功用一樣跟上面分開
// ------------------------------
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 看到改變過的物件 並將改為 50000 跟上面不符合 因為做 update 會直接改變 上面的validators不會跑 所以要用別種方式
Student.findOneAndUpdate(
{ name: "Jay Ren" },
{ "scholarship.merit": 3500 },
{ new: true, runValidators: true } // 設定就會跟著跑上面設定的 validators 因為加了 runValidators: true 不符合 就會報錯
)
.then((meg) => {
console.log(meg);
})
.catch((e) => {
console.log("Update failed");
console.log(e);
});
// find 先把它註解掉 以上的物件 save 先註解掉 在執行下面的 find 查看長怎樣
// Student.find().then((data) => {
// console.log(data);
// });
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
// -----------------------------------
// -------------------------------
// // 第五種的功用一樣跟上面分開
// Instance Method
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create an instance method 運用這個定義的變數在上面 studentSchema 變成函數
// 可以運用下方執行
studentSchema.methods.totalScholarship = function () {
return this.scholarship.merit + this.scholarship.other;
};
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 使用方式 method 上面定義一個函數 運用下方找到一個獎學金加總
Student.findOne({ name: "Jay Ren" })
.then((data) => {
let result = data.totalScholarship(); // 把她回傳值放在變數裡面
console.log(result); // 執行後他們的加總為 scholarship 3500
})
.catch((e) => {
console.log("error");
console.log(e);
});
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
// -----------------------------------
// -----------------------------------
// // 第六種的功用一樣跟上面分開
// --------------------------------
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create an instance method 運用這個定義的變數在上面 studentSchema 變成函數
// 可以運用下方執行
studentSchema.methods.totalScholarship = function () {
return this.scholarship.merit + this.scholarship.other;
};
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 使用方式 method 上面定義一個函數 運用下方找到所有獎學金加總 迴圈寫法 ` ` 運用這個符號鍵盤 1 的左邊
Student.find({}).then((data) => {
data.forEach((oneStudent) => {
console.log(
`${
oneStudent.name
} has total scholarship ${oneStudent.totalScholarship()}.`
);
});
});
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
// -----------------------
// -----------------------
// // 第七種的功用一樣跟上面分開
// ------------------------
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create an instance method 運用這個定義的變數在上面 studentSchema 變成函數
// 可以運用下方執行
studentSchema.methods.totalScholarship = function () {
return this.scholarship.merit + this.scholarship.other;
};
// 如果說年紀加一 他們 age 就加一
studentSchema.methods.addAge = function () {
this.age++;
};
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 讓物件的一個人增加他的age 運用上方的 addAge 原本年齡 21 變 22
Student.findOne({ name: "John Lee" })
.then((data) => {
data.addAge();
console.log(data);
})
.catch((e) => {
console.log("error");
console.log(e);
});
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
//----------------------------------
//----------------------------------
// Static Method 他是屬於 model
// -----------------------
// -----------------------
// // 第八種的功用一樣跟上面分開
// ------------------------
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create an instance method 運用這個定義的變數在上面 studentSchema 變成函數
// 可以運用下方執行
studentSchema.methods.totalScholarship = function () {
return this.scholarship.merit + this.scholarship.other;
};
// 如果說年紀加一 他們 age 就加一
studentSchema.methods.addAge = function () {
this.age++;
};
// create a static method 把學校所有學生獎金都歸零 只留下一個物件 this 指向 Student 所以 updataMany 是沒有問題的
studentSchema.statics.setOtherToZero = function () {
return this.updateMany({}, { "scholarship.other": 0 });
};
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 使用這個 下面的 find 要註解掉
// Student.setOtherToZero()
// .then((meg) => {
// console.log(meg); // 它是源自於 return this.updateMany({}, { "scholarship.other": 0 });這個函數
// })
// .catch((e) => {
// console.log(e);
// });
// 使用以上 下面要註解 功用為 把 other 都歸零了 以下為尋找方式
Student.find({}).then((data) => {
console.log(data);
});
// 讓物件的一個人增加他的age 運用上方的 addAge 原本年齡 21 變 22
Student.findOne({ name: "John Lee" })
.then((data) => {
data.addAge();
console.log(data);
})
.catch((e) => {
console.log("error");
console.log(e);
});
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
//---------------------------------------
----------------------------------------
//---------------------------------------
// // // 第九種的功用一樣跟上面分開
// Middleware 方式 假如說有人在你的系統註冊 有成功或失敗 想記錄一下使用者使用什麼發生了什麼問題這樣
// 做類似的功用
const express = require("express");
const app = express();
const ejs = require("ejs");
const mongoose = require("mongoose");
const fs = require("fs"); // file system 我們可以用這個功能寫一些文件
// connect to mongoDB
mongoose
.connect("mongodb://127.0.0.1:27017/exampleDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB.");
})
.catch((err) => {
console.log("Connection Failed.");
console.log(err);
});
// define a schema (定義) 為甚麼要用這種方式 可以去設定 某個值是否有效(Validators)
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "You forgot enter the name of this student."], // 就是一定要設定他的名字 沒有輸入名字就會有內容顯示這段英文
maxlenght: [15, "Name is too long"], // 如果名字超過15各字就會出現這段英文報錯
},
age: {
type: Number,
required: true,
max: 100, // 設定最大年齡
default: 18, // 如果沒有寫任何值 年齡就是 18 歲
},
major: {
type: String,
enum: [
"Chem",
"Elactrical Engineering",
"Computer Science",
"Law",
"undecided",
], // 他的主修只能是其中裡面的一個 跳脫這幾個就不會成立
default: "undecided", // 就是還沒決定的意思
},
scholarship: {
merit: {
type: Number,
default: 0, // 預設 0
min: [0, "Are you trying to enter negative numbers?"], // 如果設定小於零會出現英文
max: 5000, // 領到 5000 是最多
},
other: {
type: Number,
min: 0,
default: 0,
},
},
});
// create an instance method 運用這個定義的變數在上面 studentSchema 變成函數
// 可以運用下方執行
studentSchema.methods.totalScholarship = function () {
return this.scholarship.merit + this.scholarship.other;
};
// 如果說年紀加一 他們 age 就加一
studentSchema.methods.addAge = function () {
this.age++;
};
// create a static method 把學校所有學生獎金都歸零 只留下一個物件 this 指向 Student 所以 updataMany 是沒有問題的
studentSchema.statics.setOtherToZero = function () {
return this.updateMany({}, { "scholarship.other": 0 });
};
// 上面有再設定一個 fs 的功能 主要在說明 pre post 功用
// define middleware 是定義在 studentSchema 上面喔
// pre 功能 就是在這事情之前我們要做甚麼 我們在嘗試 save 這個 都會執行以下的
studentSchema.pre("save", async function () {
fs.writeFile("record.txt", "One data is trying to be saved", (e) => {
if (e) throw e;
});
});
// --------------
// 也可以 post
studentSchema.post("save", async function () {
fs.writeFile("record.txt", "One data has been saved", (e) => {
if (e) throw e; // 成功的話會顯示這個英文
});
});
// create a model for students --- model 後面的 String 一定開頭要大寫且不是複數因為它會自動把第一個字變小寫在把一整個字變成複數
const Student = mongoose.model("Student", studentSchema);
// 做一個物件 (Object)
const newStudent = new Student({
name: "Zech Peter",
age: 27,
major: "Chem",
scholarship: { merit: 0, other: 0 },
});
// 做一個 save 的動作 save 成功的話 就會有一個新寫入的文件 然後被儲存
newStudent
.save()
.then(() => {
console.log("saved");
})
.catch((e) => {
console.log("not saved");
fs.writeFile("record.txt", "Data is not saved", (e) => {
if (e) throw e; // 失敗的話就會看到有一個文件 然後顯示上面英文 顯示註冊失敗
});
});
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.listen(3000, () => {
console.log("Server is running on port 3000.");
});
以上來自線上課程 Udemy 網頁開發的重點筆記分享^^
感謝大家觀看~~~~~~~~~~~~

好文~知識含金量很高好文~感謝分享~您辛苦了~謝謝您!
謝謝好友的讚賞 ^^ 看文章也辛苦了唷 也謝謝觀賞本文 ^^
很專業的課程 感謝分享!
不會唷 謝謝好友的觀賞^^
整理的很詳盡 感謝分享
不會唷謝謝好友觀賞^^
謝謝分享、敘述得很詳細
感謝好友的觀賞唷XD 希望對您有幫助