MongoDB

Mongoose 是MongoDB 的前端,MongoDB 是一個使用面向文檔數據模型的開源NoSQL 數據庫。
npm 官網=>搜尋 mongoose
mongoose
安裝mongoose

1
npm i mongoose

MongoDB官網
//如圖

Accept Privacy Policy & Teams of Service
譯:接受隱私政策和服務條款
點選
點選建立資料庫Build the DataBase
選擇Free 免費,選擇地區並創建
取得使用者帳號與密碼
你想從哪裡連接?
將條目添加到您的 IP 訪問列表
IP地址 / 描述 0.0.0.0/0 / anyone can access
Connect DataBase 連接資料庫
選取Drivers
取得資料庫連結網址:
mongodb+srv://使用者帳號:此專案密碼@網址/?retryWrites=true&w=majority

環境變數:在程式剛啟動時,就可以載入require(‘dotenv’).config();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//express
const express = require('express')
//資料庫
const mongoose = require('mongoose')
//環境變數
require('dotenv').config()
const user = process.env.DB_USER;
const password = process.env.DB_PASS;
const host = process.env.DB_HOST;
const project = process.env.MONGO_PROJECT;
const retryWrites = process.env.MONGO_RETRY_WRITES;
const connectionString = `mongodb+srv://${user}:${password}@${host}/${project}?retryWrites=${retryWrites}&w=majority`;
const connectionString = `mongodb+srv://${user}:${password}@${host}/?retryWrites=${retryWrites}&w=majority`;
mongoose.set("strictQuery", false)

mongoose.connect(connectionString,{serverSelectionTimeoutMS: 5000})
.then(() => {
console.log('連結mongoose');
})
.catch((err) => {
console.log(err.message);
});

const app = express()

app.use(express.json())
// express 網址編碼 中內置的一種方法,用於將傳入的 Request Object 識別為strings 或 arrays; extended=>廣大的。

app.use(express.urlencoded({ extended: false }))


const api = require('./routes/api')
app.use('/api', api)

const auth = require('./routes/auth')
app.use('/auth', auth)


app.get('/', (req, res) => {
res.send('Hello Node Api!')
})

const PORT = process.env.PORT || 8080;


app.listen(PORT, () => console.log(`服務器正在監聽端口 ${PORT}`));

module.exports = app;

CRUD

一.新增models/newModel.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const mongoose = require('mongoose')
//Mongoose對MongoDB的操作涉及三個層面:Schema, Model與Entity
//Schema是資料文件的骨架,本身不影響資料庫,用來產生Model
//Model是用Schema產生的模型。
//Entity是用Model創建的實作。
//Model與Entity的操作會影響資料庫。

const newSchema = mongoose.Schema(
{
subject: {
type: String,
required: [true, "Please enter subject"]
},
image: {
type: String,
required: false,
},
content: {
type: String,
required: false,
}
},
{
timestamps: true
}
)


const New = mongoose.model('News', newSchema);

module.exports = New;

二.index.js,載入newModel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const express = require('express')
const mongoose = require('mongoose')
const New = require('./models/newModel')
//環境變數
require('dotenv').config()
const user = process.env.DB_USER;
const password = process.env.DB_PASS;
const host = process.env.DB_HOST;
const project = process.env.MONGO_PROJECT;
const retryWrites = process.env.MONGO_RETRY_WRITES;
const connectionString = `mongodb+srv://${user}:${password}@${host}/${project}?retryWrites=${retryWrites}&w=majority`;

mongoose.set("strictQuery", false)

mongoose.connect(connectionString,{serverSelectionTimeoutMS: 5000})
.then(() => {
console.log('連結mongoose');
})
.catch((err) => {
console.log(err.message);
});

const app = express()

// Json格式
app.use(express.json())
// express 中內置的一種方法,用於將傳入的 Request Object 識別為strings 或 arrays。
app.use(express.urlencoded({extended: false}))


//建立Create =>New.create
app.post('/new', async(req, res) => {
try {
const news = await New.create(req.body)
res.status(200).json(news);

} catch (error) {
console.log(error.message);
res.status(500).json({message: error.message})
}
})
//Read news All =>New.find({})
app.get('/news', async(req, res) => {
try {
const news = await New.find({});
res.status(200).json(news);
} catch (error) {
res.status(500).json({message: error.message})
}
})
//Read news id=> New.findById(id)
app.get('/news/:id', async(req, res) =>{
try {
const {id} = req.params;
const news = await New.findById(id);
res.status(200).json(news);
} catch (error) {
res.status(500).json({message: error.message})
}
})

//updatedNews => New.findByIdAndUpdate(id, req.body)
app.put('/news/:id', async(req, res) => {
try {
const {id} = req.params;
const newR = await New.findByIdAndUpdate(id, req.body);
// we cannot find any news in database
if(!newR){
return res.status(404).json({message: `cannot find any news with ID ${id}`})
}
const updatedNews = await New.findById(id);
res.status(200).json(updatedNews);

} catch (error) {
res.status(500).json({message: error.message})
}
})

//Delete news id =>New.findByIdAndDelete(id)
app.delete('/news/:id', async(req, res) =>{
try {
const {id} = req.params;
const test = await New.findByIdAndDelete(id);
if(!test){
return res.status(404).json({message: `沒有發現任何 News ID ${id}`})
}
res.status(200).json(test);

} catch (error) {
res.status(500).json({message: error.message})
}
})

const PORT = process.env.PORT || 8080;


app.listen(PORT, () => console.log(`服務器正在監聽端口 ${PORT}`));

module.exports = app;

Render部署

Render
選取WebServer

箭頭內貼入Git庫網址

在Name框中,輸入一個簡短的名字來標識你的網站。



如果你的入口文件是 index.js,在Start Command中填寫node index.js。
如果你的入口是 server.js,在Start Command中填寫node server.js

再向下滑動頁面會看到Advanced按鈕

如果你的應用使用了環境變量,你可以在Advanced設置中輸入。也可以在這裡添加 .env文件,這樣就不用你手動一個一個地添加。

處理Bug

環境變數內新增

NODE_VERSION 14.20.1