harryd123
New Coder
I'm hoping somebody can put me out of my misery. I'm following a tutorial to build a blogging website but have run into trouble when trying to post to my database.
link:
I've copied the code line form his tutorial mostly, and have mongoDB hooked up correctly (I think). Yet when I press save, nothing is posted, nothing shows up in the database thats been created, and the form isn't redirected. I think because an object isn't been created, it can't find an ID and is redirecting me to the same page.
In my implementation I actually modified the code quite a bit, but when running into this issue I decided to recreate his project line by line - only to get the same error. Feels like it has to be something to do with how my DB is configured?
Please can someone help? Thanks!
Routes file is here:
link:
I've copied the code line form his tutorial mostly, and have mongoDB hooked up correctly (I think). Yet when I press save, nothing is posted, nothing shows up in the database thats been created, and the form isn't redirected. I think because an object isn't been created, it can't find an ID and is redirecting me to the same page.
In my implementation I actually modified the code quite a bit, but when running into this issue I decided to recreate his project line by line - only to get the same error. Feels like it has to be something to do with how my DB is configured?
Please can someone help? Thanks!
Routes file is here:
Code:
const express = require('express')
const Blog = require('./../models/blog')
const router = express.Router()
router.get('/new', (req, res) => {
res.render('blogs/new', { blog: new Blog() })
})
router.get('/edit/:id', async (req, res) => {
const blog = await Blog.findById(req.params.id)
res.render('blogs/edit', { blog: blog })
})
router.get('/:slug', async (req, res) => {
const blog = await Blog.findOne({ slug: req.params.slug })
if (blog == null) res.redirect('/')
res.render('blogs/show', { blog: blog })
})
router.post('/', async (req, res, next) => {
req.blog = new Blog()
next()
}, saveblogAndRedirect('show'))
router.put('/:id', async (req, res, next) => {
req.blog = await Blog.findById(req.params.id)
next()
}, saveblogAndRedirect('edit'))
router.delete('/:id', async (req, res) => {
await Blog.findByIdAndDelete(req.params.id)
res.redirect('/')
})
function saveblogAndRedirect(path) {
return async (req, res) => {
let blog = req.blog
blog.title = req.body.title
blog.description = req.body.description
blog.markdown = req.body.markdown
try {
blog = await blog.save()
res.redirect(`/blogs/${blog.slug}`)
} catch (e) {
res.render(`blogs/${path}`, { blog: blog })
}
}
}
module.exports = router