-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
52 lines (42 loc) · 1.38 KB
/
app.js
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
const express = require('express');
const { MongoClient, ObjectId } = require('mongodb');
const path = require('path');
const app = express();
const port = 3000;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
let db;
async function connectToMongo() {
try {
await client.connect();
db = client.db('notes_app');
console.log('Connected to MongoDB');
} catch (err) {
console.error('Error connecting to MongoDB', err);
}
}
connectToMongo();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/notes', async (req, res) => {
const notes = await db.collection('notes').find({}).toArray();
res.json(notes);
});
app.post('/notes', async (req, res) => {
const note = req.body;
await db.collection('notes').insertOne(note);
res.status(201).send('Note added successfully');
});
app.delete('/notes/:id', async (req, res) => {
const id = req.params.id;
try {
await db.collection('notes').deleteOne({ _id: new ObjectId(id) });
res.status(200).send('Note deleted successfully');
} catch (err) {
console.error('Error deleting note', err);
res.status(500).send('Internal server error');
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});