3-2编写数据库交互代码
ch3-项目数据库实现
编写数据库交互(增改查)代码
(定义好)模式schema,并(编译好)模型model之后,再利用mongoose模块连接本地数据库
需要在本地预先安装MongoDB
app.js
var express = require('express');
// var path = require('path'); //静态资源目录,新版express要独立安装static
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var _ = require('underscore'); //根据新对象覆盖老对象的值
var Movie = require('./models/movie'); //取得模型
var port = process.env.PORT || 3000;
var app = express();
mongoose.connect('mongodb://localhost/imooc'); //连接数据库
app.set('views', './views/pages/'); //修改视图模板目录
app.set('view engine', 'jade');
// app.use(express.bodyParser()); //表单数据格式化,新版express不捆绑bodyParser
// app.use(express.static(path.join(__dirnamr, 'bower_components'))); //告诉express页面请求中样式和脚本的请求去path中查找
app.use(bodyParser.urlencoded());
// app.use(bodyParser.json({limit: '1mb'})); //body-parser 解析json格式数据
// app.use(bodyParser.urlencoded({ //此项必须在 bodyParser.json 下面,为参数编码
// extended: true
// }));
app.use(serveStatic('bower_components'));
app.listen(port);
console.log('imooc started on port ' + port);
//路由
//index page
app.get('/', function(req, res){ //路由规则和URL地址相匹配
Movie.fetch(function(err, movies){ //获取所有数据
if(err){
console.log(err);
}
res.render('index', { //渲染模板
title: 'imooc 首页',
movies: movies
});
});
});
//detail page
app.get('/movie/:id', function(req, res){
var id = req.params.id;
Movie.findById(id, function(err, movie){ //获取指定id电影数据
res.render('detail', {
title: 'imooc ' + movie.title,
movie: movie
});
});
});
//admin page
app.get('/admin/movie', function(req, res){
res.render('admin', {
title: 'imooc 录入页',
movie: {
doctor: '',
country: '',
title: '',
year: '',
poster: '',
language: '',
flash: '',
summary: ''
}
});
});
//admin update movie
app.get('/movie/update/:id', function(req, res){
var id = req.params.id;
if(id){
Movie.findById(id, function(err, movie){
res.render('admin', {
title: 'imooc 后台更新页',
movie: movie
});
});
}
});
//admin post movie
app.post('/admin/movie/new', function(req, res){
var movieObj = req.body.movie;
var id = movieObj._id;
if(id !== 'undefined'){
Movie.findById(id, function(err, movie){
if(err){
console.log(err);
}
_movie = _.extend(movie, movieObj);
_movie.save(function(err, movie){
if(err){
console.log(err);
}
res.redirect('/movie/' + movie._id);
});
});
}else{
_movie = new Movie({
doctor: movieObj.doctor,
title: movieObj.title,
country: movieObj.country,
language: movieObj.language,
year: movieObj.year,
poster: movieObj.poster,
summary: movieObj.summary,
flash: movieObj.flash,
});
_movie.save(function(err, movie){ //存储数据
if(err){
console.log(err);
}
res.redirect('/movie/' + movie._id);
});
}
});
//list page
app.get('/admin/list/', function(req, res){
Movie.fetch(function(err, movies){
if(err){
console.log(err);
}
res.render('list', {
title: 'imooc 列表页',
movies: movies
});
});
});