📝

Building a Blog with MongoDB, Express, and Node

Jul 22, 2024

Building a Blog with MongoDB, Express, and Node

Introduction

  • Presenter: Kyle from Web Dev Simplified
  • Objective: Learn to build a blog with MongoDB, Express, and Node.js, applicable to any app you want to create

Setting Up the Server

  1. Initialize npm
    • Command: npm init -y for a basic package.json
  2. Install Dependencies
    • express: For server
    • mongoose: For MongoDB interactions
    • ejs: For templating
  3. Install Dev Dependencies
    • nodemon: For auto-refreshing the server on file changes
    • Add script: "dev": "nodemon server.js"

Basic Server Setup

  1. Create server file: server.js
    • Import express and create app instance: const express = require('express'); const app = express();
    • Set up a listening port: app.listen(5000)
  2. Basic Routing
    • Define a default route that sends 'Hello World': app.get('/', (req, res) => { res.send('Hello World'); });
  3. Set View Engine
    • Set ejs as the view engine: app.set('view engine', 'ejs');
  4. Create Views Folder
    • Create an index.ejs file under views/ <!DOCTYPE html> <html> <head> <title>Blog</title> </head> <body> <h1>This is HTML</h1> </body> </html> Render this view in the default route: app.get('/', (req, res) => { res.render('index'); });

Creating Routes for Articles

  1. Structure Routes
    • Create a routes folder and articles.js file
    • Define routes such as viewing, editing, and deleting articles
    • Use express router: const router = express.Router();
  2. Middleware for JSON Parsing
    • Add middleware to parse JSON and URL-encoded data: app.use(express.json()); app.use(express.urlencoded({ extended: false }));
  3. API Endpoints
    • Example for getting all articles: router.get('/', async (req, res) => { const articles = await Article.find().sort({ createdAt: 'desc' }); res.render('articles/index', { articles: articles }); });

Database Setup

  1. Connect to MongoDB with Mongoose
    • mongoose.connect('mongodb://localhost/blog', { useNewUrlParser: true, useUnifiedTopology: true });
  2. Define Article Schema
    • Create a models folder and article.js file: const mongoose = require('mongoose'); const articleSchema = new mongoose.Schema({ title: { type: String, required: true }, description: String, markdown: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Article', articleSchema);

Forms and Views

  1. Forms Partial for Articles
    • Create reusable form partial _form_fields.ejs for use in new and edit views
    • Render this partial in views: <%- include('_form_fields'); %>
    • Ensure fields are marked as required in the form
  2. Creating Articles
    • Define post route to create new articles and save to database router.post('/', async (req, res) => { let article = new Article({ title: req.body.title, description: req.body.description, markdown: req.body.markdown }); try { article = await article.save(); res.redirect(`/articles/${article.id}`); } catch (e) { res.render('articles/new', { article: article }); } });