定義數據模型 使用mongoose操作資料庫 "可參考文檔進行使用" ...
定義數據模型
import mongoose from 'mongoose'
mongoose.connect('mongodb://localhost/edu')
const advertSchema = mongoose.Schema({
title: { type: String, required: true },
image: { type: String, required: true },
link: { type: String, required: true },
start_time: { type: Date, required: true },
end_time: { type: Date, required: true },
create_time: { type: Date, default: Date.now },
last_modified: { type: Date, default: Date.now }
})
export default mongoose.model('Advert', advertSchema)
使用mongoose操作資料庫
import express from 'express'
import Advert from '../models/advert'
// 創建一個路由容器,將所有的路由中間件掛載給路由容器
const router = express.Router()
router.get('/advert', (req, res, next) => {
res.render('advert_list.html')
})
router.get('/advert/add', (req, res, next) => {
res.render('advert_add.html')
})
/**
* POST /advert/add
* body: { title, image, link, start_time, end_time }
*/
router.post('/advert/add', (req, res, next) => {
// 1. 接收表單提交的數據
const body = req.body
// 2. 操作資料庫
const advert = new Advert({
title: body.title,
image: body.image,
link: body.link,
start_time: body.start_time,
end_time: body.end_time,
})
advert.save((err, result) => {
if (err) {
return next(err)
}
res.json({
err_code: 0
})
})
})
router.get('/advert/list', (req, res, next) => {
Advert.find((err, docs) => {
if (err) {
return next(err)
}
res.json({
err_code: 0,
result: docs
})
})
})
// /advert/one/:advertId 是一個模糊匹配路徑
// 可以匹配 /advert/one/* 的路徑形式
// 例如:/advert/one/1 /advert/one/2 /advert/one/a /advert/one/abc 等路徑
// 但是 /advert/one 或者 /advert/one/a/b 是不行的
// 至於 advertId 是自己起的一個名字,可以在處理函數中通過 req.params 來進行獲取
router.get('/advert/one/:advertId', (req, res, next) => {
Advert.findById(req.params.advertId, (err, result) => {
if (err) {
return next(err)
}
res.json({
err_code: 0,
result: result
})
})
})
// /advert/edit
router.post('/advert/edit', (req, res, next) => {
Advert.findById(req.body.id, (err, advert) => {
if (err) {
return next(err)
}
const body = req.body
advert.title = body.title
advert.image = body.image
advert.link = body.link
advert.start_time = body.start_time
advert.end_time = body.end_time
advert.last_modified = Date.now()
// 這裡的 save 因為內部有一個 _id 所以這裡是不會新增數據的,而是更新已有的數據
advert.save((err, result) => {
if (err) {
return next(err)
}
res.json({
err_code: 0
})
})
})
})
router.get('/advert/remove/:advertId', (req, res, next) => {
Advert.remove({ _id: req.params.advertId }, err => {
if (err) {
return next(err)
}
res.json({
err_code: 0
})
})
})
export default router