var express = require('express')
var mongoose = require('mongoose')
var _ = require('underscore')
var Movie = require('./models/movie')
var bodyParser = require('body-parser')
var port = process.env.PORT || 3000 //process 是全局变量
var app = express()
mongoose.connect('mongodb://localhost/imooc')
app.set('views', './views/pages')
app.set('view engine', 'jade')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/views'))
app.use('/bower_components', express.static(__dirname + '/bower_components'))
app.listen(port)
console.log('imooc started on port ' + port)
// 首页
app.get('/', function(req, res) {
Movie.fetch(function(err, movies) {
if (err) {
console.log(err)
}
res.render('index', {
title: ' imooc 首页',
movies: movies
})
})
})
// detail
app.get('/movie/:id', function(req, res) {
var id = req.params.id
Movie.findById(id, function(err, movie) {
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('admin/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) {
console.log(req.body)
// console.log(req.body.movie)
var id = req.body.movie._id
var movieObj = req.body.movie
var _movie
if (id !== 'undefined') {
Movie.findById(id, function(err, movie) {
if (err) {
console.log(err);
}
_movie = _.extend(movie, movieObj)
console.log(movie + "这里是98行c")
console.log(_movie + "这里是99行c")
//复制 movieObj movie 对象上, 然后返回 movie 对象.复制是按顺序的, 所以后面的对象属性会把前面的对象属性覆盖掉(如果有重复).
_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
})
})
})