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)
可參考文檔進行使用javascript
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