1:當前環境node
y@y:~$ node --version && express -V && mongo --version v0.12.2 4.9.0 MongoDB shell version: 2.4.9 y@y:~$
2:新建工程目錄mongodb
y@y:express-test$ express demo01 y@y:express-test$ cd demo01 && npm install
使用bower下載bootstrap:
y@y:public$ bower install bootstrap
在package.json中加入mongodb依賴:shell
{ "name": "demo01", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "express": "~4.9.0", "body-parser": "~1.8.1", "cookie-parser": "~1.3.3", "morgan": "~1.3.0", "serve-favicon": "~2.1.3", "debug": "~2.0.0", "jade": "~1.6.0", "mongodb": "~2.0.33", "monk": "~1.0.1" } }
再次執行:npm installexpress
3:工程代碼結構npm
(1)app.jsjson
// 加載依賴庫 var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); //mongodb config //var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/test'); // 加載路由控制 var routes = require('./routes/index'); var users = require('./routes/users'); // 建立項目實例 var app = express(); // 定義jade模板引擎和模板文件位置 app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // 定義網站圖標 //app.use(favicon(__dirname + '/public/favicon.ico')); // 定義日誌和輸出級別 app.use(logger('dev')); // 定義數據解析器 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // 定義cookie解析器 app.use(cookieParser()); // 定義靜態文件目錄 app.use(express.static(path.join(__dirname, 'public'))); //讓db訪問路由 app.use(function(req,res,next){ req.db = db; next(); }); // 匹配路徑和路由 app.use('/', routes); app.use('/user', users); // 404錯誤處理 app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // 開發環境,500錯誤處理和錯誤堆棧跟蹤 if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // 生產環境,500錯誤處理 app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); // 輸出模型app module.exports = app;
(2)路由users.jsbootstrap
var express = require('express'); var router = express.Router(); /** * 用戶列表 * http://127.0.0.1:3000/user/list */ router.get('/list', function(req, res) { var db = req.db; db.get('user').find({},{},function(err,docs){ if(err){ errHandler(res,err); }else{ res.render('users/list',{ title: '用戶列表', userlist: docs }); } }); }); /** * 添加新用戶操做界面 * http://127.0.0.1:3000/user/add */ router.get('/add', function(req, res) { res.render('users/add'); }); /** * 修改用戶信息界面 */ router.get('/edit/:id', function(req,res){ var db = req.db; db.get('user').findOne({_id:req.params.id},{},function(err,doc){ if(err){ errHandler(res,err); }else{ res.render('users/edit', {user: doc}); } }); }); /** * 修改用戶信息 */ router.post('/update', function(req,res){ var db = req.db; var _id = req.body._id; var name = req.body.name; var email = req.body.email; db.get('user').updateById(_id, {'name':name,'email':email}, function(err,doc){ if(err){ errHandler(res,err); }else{ res.redirect('list'); } }); }); /** * 保存新添加的用戶信息 */ router.post('/save', function(req,res){ var db = req.db; var name = req.body.name; var email = req.body.email; db.get('user').insert( { 'name': name, 'email': email }, function(err,doc){ if(err){ errHandler(res,err); }else{ res.redirect('list'); } } ); }); /** * 根據_id刪除 */ router.get('/delete/:id', function(req,res){ var db = req.db; db.get('user').remove({_id:req.params.id},function(err,doc){ if(err){ errHandler(res,err); }else{ res.render('info',{info:'刪除成功!',url:'http://127.0.0.1:3000/user/list'}); } }); }); /** * 錯誤處理 * @param res * @param err */ function errHandler(res,err){ res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }; module.exports = router;
(3)users/list.jadecookie
extends ../layout
block content
div.container
h3.text-center.text-primary 用戶列表
hr
a.btn.btn-primary.btn-sm(href='add') 增長
table.table.table-bordered.table-condensed.table-hover
thead
tr.bg-info
th.text-center.col-xs-4 用戶名
th.text-center.col-xs-5 郵箱
th.text-center.col-xs-3 操做
tbody
each user, i in userlist
tr.text-center
td= user.name
td= user.email
td
a.btn.btn-danger.btn-sm.margin-left(href='delete/'+user._id) 刪除
a.btn.btn-warning.btn-sm.margin-left(href='edit/'+user._id) 修改
(4)users/add.jadeapp
extends ../layout
block content
div.container
h3.text-center.text-primary 添加用戶
hr
form(name="addUserForm",method="post",action="/user/save")
div.form-group
label(for='name') 用戶名
input#name.form-control(name='name',placeholder='用戶名')
div.form-group
label(for='email') 郵箱
input#email.form-control(name='email',type='email',placeholder='郵箱地址')
div.text-center
button.btn.btn-primary.margin-right(type='submit') 保存
button.btn.btn-default.margin-left(type='reset') 重置
(5)users/edit.jadepost
extends ../layout
block content
div.container
h3.text-center.text-primary 修改用戶信息
hr
form(name="editUserForm",method="post",action="/user/update")
input(type='hidden',name='_id',value=user._id)
div.form-group
label(for='name') 用戶名
input#name.form-control(name='name',placeholder='用戶名', value=user.name)
div.form-group
label(for='email') 郵箱
input#email.form-control(name='email',type='email',placeholder='郵箱地址', value=user.email)
div.text-center
button.btn.btn-primary.margin-right(type='submit') 保存
button.btn.btn-default.margin-left(type='reset') 重置
(6)info.jade
extends layout
block content
div.container.text-center
h1.text-warning=info
a.btn.btn-primary(href=url) 返回