-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (54 loc) · 1.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');
const _ = require('lodash');
app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));
mongoose.connect(process.env.MONGO_URL);
const postsSchema = new mongoose.Schema({ title: 'string', content: 'string', postBy: 'string' });
const Post = mongoose.model('Post', postsSchema);
app.get('/', function (req, res) {
Post.find({}, function (err, foundPosts) {
res.render("home", {posts: foundPosts});
});
});
app.get('/about', function (req, res) {
res.render("about");
});
app.get('/contact', function (req, res) {
res.render("contact");
});
app.get('/compose', function (req, res) {
res.render("compose");
});
app.post('/compose', function (req, res) {
const postToPublish = new Post({
title: req.body.postTitle,
content: req.body.postContent,
postBy: req.body.postBy
});
postToPublish.save(function (err) {
if (!err) {
res.redirect('/');
}
});
});
app.get('/posts/:postId', function (req, res) {
const requestedPost = req.params.postId;
Post.findOne({_id: requestedPost}, function (err, foundPost) {
if (!err) {
res.render("post", {title: foundPost.title, content: foundPost.content, postBy: foundPost.postBy});
}
});
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function() {
console.log("Server started successfully.");
});