-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (63 loc) · 1.87 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const express = require("express");
const mongoose = require("mongoose");
const Todo = require("./model/todo");
// Load environment variables from .env file
require("dotenv").config();
// Create an Express application
const app = express();
const port = 3001;
//middleware provided by Express to parse incoming JSON requests.
app.use(express.json());
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log("MongoDB is connected!");
}).catch((error) => {
console.error("MongoDB connection error:", error);
});
// Create an todo item
app.post("/todos/create", async (req, res) => {
try {
const newTodo = await Todo.create(req.body);
res.status(201).json(newTodo);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
// Read all todos
app.get("/todos", async (req, res) => {
try {
const todos = await Todo.find();
res.status(200).json(todos);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
// Update a todo by ID
app.put("/todos/:id", async (req, res) => {
try {
const updatedTodo = await Todo.findByIdAndUpdate(req.params.id, req.body, {
new: true,
});
res.status(200).json(updatedTodo);
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
// Delete a todo by ID
app.delete("/todos/:id", async (req, res) => {
try {
await Todo.findByIdAndDelete(req.params.id);
res.status(204).send();
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
// Start the server on port 3001
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});