임태민

Update project directory

- Update backend files
......@@ -4,6 +4,7 @@ const bodyParser = require('body-parser');
const methodOverride = require('body-parser');
const app = express();
// DB Setting
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
......@@ -16,16 +17,18 @@ mongoose.connect('mongodb+srv://Mapmory_admin:admin@cluster0.ncnjj.mongodb.net/P
// Store DB in the variable 'db'
var db = mongoose.connection;
// If DB is opened successfully
db.once('open', function(){
console.log('DB connected');
});
});
// if DB is failed to open
db.on('error', function(err){
console.log('DB ERROR : ', err);
});
// Settings
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
......@@ -34,9 +37,13 @@ app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride('_method'));
// Routes
app.use('/', require('./routes/home'));
app.use('/posts', require('./routes/posts'));
// Server
var port = 3000;
app.listen(port, function(){
console.log('server on! http://localhost:' + port);
......
const mongoose = require('mongoose');
// Declare the schemea of post
var postSchema = mongoose.Schema({
title:{type:String, required:true},
body:{type:String, required:true},
createdAt:{type:Date, default:Date.now},
updatedAt:{type:Date},
});
// Declare the variable
var Post = mongoose.model('post', postSchema);
// Export module
module.exports = Post;
\ No newline at end of file
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
// Post home
router.get('/', function(req, res){
Post.find({})
.sort('-createdAt')
.exec(function(err, posts){
if(err){return res.json(err)};
res.render('posts/index', {posts:posts});
});
});
// Post new
router.get('/new', function(req, res){
res.render('posts/new');
})
// Post create
router.post('/', function(req, res){
Post.create(req.body, function(err, post){
if(err){return res.json(err)};
res.redirect('/posts');
});
});
// Post show
router.get('/:id', function(req, res){
Post.findOne({_id:req.params.id}, function(err, post){
if(err){return res.json(err)};
res.render('posts/show', {post:post});
});
});
// Post edit
router.get('/:id/edit', function(req, res){
Post.findOne({_id:req.params.id}, function(err, post){
if(err){return res.join(err)};
res.render('posts/edit', {posts:post});
});
});
// Post update
router.get('/:id', function(req, res){
req.body.updatedAt = Date.now();
Post.findOneAndUpdate({_id:req.params.id}, req.body, function(err, post){
if(err){return res.join(err)};
res.redirect('posts/' + req.params.id);
});
});
// Post delete
router.delete('/:id', function(req, res){
Post.deleteOne({_id:req.params.id}, function(err){
if(err){return res.join(err)};
res.redirect('/posts');
});
});
// Export module
module.exports = router;
\ No newline at end of file