Jul 22, 2024
npm init -y for a basic package.jsonexpress: For servermongoose: For MongoDB interactionsejs: For templatingnodemon: For auto-refreshing the server on file changes"dev": "nodemon server.js"server.js
const express = require('express'); const app = express();app.listen(5000)app.get('/', (req, res) => {
res.send('Hello World');
});
app.set('view engine', 'ejs');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');
});
routes folder and articles.js fileconst router = express.Router();app.use(express.json());
app.use(express.urlencoded({ extended: false }));
router.get('/', async (req, res) => {
const articles = await Article.find().sort({ createdAt: 'desc' });
res.render('articles/index', { articles: articles });
});
mongoose.connect('mongodb://localhost/blog', { useNewUrlParser: true, useUnifiedTopology: true });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);
_form_fields.ejs for use in new and edit views<%- include('_form_fields'); %>
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 });
}
});