-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.js
More file actions
55 lines (45 loc) · 1.22 KB
/
Copy pathnode.js
File metadata and controls
55 lines (45 loc) · 1.22 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
47
48
49
50
51
52
53
54
55
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/notesDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Define Schema
const noteSchema = new mongoose.Schema({
title: String,
content: String,
createdAt: { type: Date, default: Date.now }
});
const Note = mongoose.model('Note', noteSchema);
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(express.static('public'));
// Routes
// Home - list all notes
app.get('/', async (req, res) => {
const notes = await Note.find();
res.render('index', { notes });
});
// Add new note
app.post('/add', async (req, res) => {
const newNote = new Note({
title: req.body.title,
content: req.body.content
});
await newNote.save();
res.redirect('/');
});
// Delete note
app.post('/delete', async (req, res) => {
const noteId = req.body.noteId;
await Note.findByIdAndDelete(noteId);
res.redirect('/');
});
// Start server
app.listen(3000, () => {
console.log('Server running on port 3000');
});