MongoDB增刪改查操作實戰案例(非模組化)
案例:使用者資訊增刪改查
- 搭建網站伺服器,實現客戶端與伺服器端的通訊
- 連線資料庫,建立使用者集合,向集合中插入文件
- 當使用者訪問
/list
時,將所有使用者資訊查詢出來 - 將使用者資訊和表格HTML進行拼接並將拼接結果響應回客戶端
- 當使用者訪問
/add
時,呈現表單頁面,並實現新增使用者資訊功能 - 當使用者訪問
/modify
時,呈現修改頁面,並實現修改使用者資訊功能 - 當使用者訪問
/delete
時,實現使用者刪除功能
程式碼(Node+模板字串+MongDB)
const http = require('http')
const mongoose = require('mongoose')
const url = require('url')
const querystring = require('querystring')
mongoose.connect('mongodb://localhost/zhangbing',{ useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('資料庫連線成功'))
.catch(() => console.log('資料庫連線失敗'))
const userSchema = new mongoose.Schema({
name:{
type:String,
required:true,
minlength:2,
maxlength:20
},
age:{
type:Number,
min:18,
max:80
},
password:String,
email:String,
hobbies:[String]
})
const User = mongoose.model('User',userSchema)
const app = http.createServer()
app.on('request', async (req,res) => {
const method = req.method;
const { pathname, query } = url.parse(req.url, true)
if (method == 'GET') {
if (pathname == '/list') {
let users = await User.find()
let list = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用者列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h6>
<a href="/add" class="btn btn-primary">新增使用者</a>
</h6>
<table class="table table-striped table-bordered">
<tr>
<td>使用者名稱</td>
<td>年齡</td>
<td>愛好</td>
<td>郵箱</td>
<td>操作</td>
</tr>
`;
users.forEach((item) => {
list += `
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>
`;
item.hobbies.forEach((item) => {
list += `<span>${item}</span>`;
})
list += `</td>
<td>${item.email}</td>
<td>
<a href="/remove?id=${item.id}" class="btn btn-danger btn-xs">刪除</a>
<a href="/modify?id=${item.id}" class="btn btn-success btn-xs">修改</a>
</td>
</tr>
`;
})
list += `</table>
</div>
</body>
</html>
`;
res.end(list)
} else if (pathname == '/add') {
let add = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用者列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>新增使用者</h3>
<form method='post' action="/add">
<div class="form-group">
<label>使用者名稱</label>
<input name="name" type="text" class="form-control" placeholder="請填寫使用者名稱">
</div>
<div class="form-group">
<label>密碼</label>
<input name="password" type="password" class="form-control" placeholder="請輸入密碼">
</div>
<div class="form-group">
<label>年齡</label>
<input name="age" type="text" class="form-control" placeholder="請填寫年齡">
</div>
<div class="form-group">
<label>郵箱</label>
<input name="email"type="email" class="form-control" placeholder="請填寫郵箱">
</div>
<div class="form-group">
<label>請選擇愛好</label>
<div>
<label class="checkbox-inline">
<input type="checkbox" value="足球" name="hobbies"> 足球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="籃球" name="hobbies"> 籃球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="橄欖球" name="hobbies"> 橄欖球
</label>
<label class="checkbox-inline">
<input type="checkbox" value="敲程式碼" name="hobbies"> 敲程式碼
</label>
<label class="checkbox-inline">
<input type="checkbox" value="抽菸" name="hobbies"> 抽菸
</label>
<label class="checkbox-inline">
<input type="checkbox" value="喝酒" name="hobbies"> 喝酒
</label>
<label class="checkbox-inline">
<input type="checkbox" value="燙頭" name="hobbies"> 燙頭
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">新增使用者</button>
</form>
</div>
</body>
</html>`;
res.end(add)
} else if (pathname == '/modify') {
let user = await User.findOne({_id:query.id})
let hobbies = ['足球','籃球','橄欖球','敲程式碼','抽菸','喝酒','燙頭', '吃飯', '睡覺', '打豆豆']
let modify = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用者列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>修改使用者</h3>
<form method='post' action="/modify?id=${user._id}">
<div class="form-group">
<label>使用者名稱</label>
<input value="${user.name}" name="name" type="text" class="form-control" placeholder="請填寫使用者名稱">
</div>
<div class="form-group">
<label>密碼</label>
<input value="${user.password}" name="password" type="password" class="form-control" placeholder="請輸入密碼">
</div>
<div class="form-group">
<label>年齡</label>
<input value="${user.age}" name="age" type="text" class="form-control" placeholder="請填寫年齡">
</div>
<div class="form-group">
<label>郵箱</label>
<input value="${user.email}" name="email"type="email" class="form-control" placeholder="請填寫郵箱">
</div>
<div class="form-group">
<label>請選擇愛好</label>
<div>
`;
hobbies.forEach (item => {
let isHobby = user.hobbies.includes(item)
if (isHobby) {
modify += `
<label class="checkbox-inline">
<input type="checkbox" value="${item}" name="hobbies" checked> ${item}
</label>`
} else {
modify += `
<label class="checkbox-inline">
<input type="checkbox" value="${item}" name="hobbies"> ${item}
</label>`
}
})
modify += `</div>
</div>
<button type="submit" class="btn btn-primary">修改使用者</button>
</form>
</div>
</body>
</html>
`;
res.end(modify)
} else if (pathname == '/remove') {
await User.findOneAndDelete({_id:query.id})
res.writeHead(301, {
Location:'/list'
})
res.end();
}
} else if (method == 'POST') {
if (pathname == '/add') {
let formData = '';
req.on('data', param => {
formData += param;
})
req.on('end', async () => {
let user = querystring.parse(formData)
await User.create(user)
res.writeHead(301, {
Location:'/list'
})
res.end();
})
} else if (pathname == '/modify') {
let formData = '';
req.on('data', param => {
formData += param;
})
req.on('end', async () => {
let user = querystring.parse(formData)
await User.updateOne({_id: query.id}, user);
res.writeHead(301, {
Location: '/list'
});
res.end();
})
}
}
})
app.listen(3000)