将 9.CRUD 系统设计 中的案例用 MongoDB 再设计一遍:
app.js
var express = require('express')
var router = require('./router')
var bodyParser = require('body-parser')
var app = express()
app.use('/node_modules', express.static('node_modules'))
app.use('/public', express.static('public'))
app.engine('html',require('express-art-template'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(router)
app.listen(3000, function () {
console.log('running 3000...')
})
router.js
var fs = require('fs')
var crud = require('./crud')
var express = require('express')
var router = express.Router()
router.get('/students', function (req, res) {
crud.find(function (err, students) {
if (err) {
return res.status(500).send('Server error.')
}
res.render('index.html', {
students: students
})
})
})
router.get('/students/new', function (req, res) {
res.render('new.html')
})
router.post('/students/new', function (req, res) {
new crud(req.body).save(function (err) {
if(err) {
return res.status(500).send('Server error.')
}
res.redirect('/students')
})
})
router.get('/students/edit', function (req, res) {
crud.findById(req.query.id, function (err, student) {
if(err) {
return res.status(500).send('Server error.')
}
res.render('edit.html', {
student: student
})
})
})
router.post('/students/edit', function (req, res) {
crud.findByIdAndUpdate(req.body.id, req.body, function (err) {
if(err) {
return res.status(500).send('Server error.')
}
res.redirect('/students')
})
})
router.get('/students/delete', function (req, res) {
crud.deleteById(req.query.id, function (err) {
if(err) {
return res.status(500).send('Server error.')
}
res.redirect('/students')
})
})
module.exports = router
crud.js
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/test')
var Schema = mongoose.Schema
var studentSchema = new Schema({
name: {
type: String,
required: true
},
gender: {
type: Number,
enum: [0, 1],
default: 0
},
age: {
type: Number
},
major: {
type: String
}
})
module.exports = mongoose.model('Student', studentSchema)