-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
84 lines (73 loc) · 1.9 KB
/
Copy pathapp.js
File metadata and controls
84 lines (73 loc) · 1.9 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const PORT = 3000;
const MONGODB_URI = "";
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define User schema
const userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
dob: Date,
});
const User = mongoose.model("User", userSchema);
// Parse incoming JSON requests
app.use(bodyParser.json());
app.use(cors());
// Handle GET request for all users
app.get("/users", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Handle GET request for one user
app.get("/users/:id", async (req, res) => {
try {
const user = await User.findById(req.params.id);
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Handle POST request to create a new user
app.post("/users", async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Handle PUT request to update an existing user
app.put("/users/:id", async (req, res) => {
try {
const user = await User.findById(req.params.id);
user.set(req.body);
await user.save();
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Handle DELETE request to delete an existing user
app.delete("/users/:id", async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});