-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
46 lines (39 loc) · 1.2 KB
/
app.js
File metadata and controls
46 lines (39 loc) · 1.2 KB
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
const express = require('express')
const handlebars = require('express-handlebars')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const app = express()
const port = 3000
// Import models defined in another file
const Item = require('./models/item')
// Connect mongodb
mongoose.connect('<MongoDB URI>', { useNewUrlParser: true }, (err, db) => {
if (err) console.log(`Error`, err)
console.log(`Connected to MongoDB`)
})
// Initialize Express settings
app.engine('handlebars', handlebars({defaultLayout: 'main'}))
app.set('view engine', 'handlebars')
app.use(bodyParser.urlencoded({extended: true}))
// Define the root '/' to show hello world
app.get('/', (req, res) => {
res.render('index')
})
// Define the endpoint '/items' to show all items
app.get('/items', (req, res) => {
Item.find((err, items) => {
if (err) return console.error(err)
res.render('items', {items: items})
})
})
// Create a new item
app.post('/create', (req, res) => {
const item = Item({
item: req.body.item
})
item.save((err, todo) => {
if (err) return console.error(err)
res.redirect('/items')
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))