-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
87 lines (76 loc) · 2.29 KB
/
Copy pathserver.js
File metadata and controls
87 lines (76 loc) · 2.29 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
85
86
87
// server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;
const MONGO_URI = process.env.MONGO_URI || 'mongodb://host.docker.internal:27017/myapp';
// Middleware
app.use(express.json());
// MongoDB Connection
mongoose.connect(MONGO_URI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
// Define a simple schema and model
const ItemSchema = new mongoose.Schema({
name: { type: String, required: true },
description: String,
createdAt: { type: Date, default: Date.now }
});
const Item = mongoose.model('Item', ItemSchema);
// Basic route
app.get('/', (req, res) => {
res.json({ message: 'Welcome to the Express API with MongoDB!' });
});
// GET all items
app.get('/api/items', async (req, res) => {
try {
const items = await Item.find();
res.json(items);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET single item
app.get('/api/items/:id', async (req, res) => {
try {
const item = await Item.findById(req.params.id);
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json(item);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST create item
app.post('/api/items', async (req, res) => {
try {
const item = new Item(req.body);
await item.save();
res.status(201).json(item);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// PUT update item
app.put('/api/items/:id', async (req, res) => {
try {
const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json(item);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// DELETE item
app.delete('/api/items/:id', async (req, res) => {
try {
const item = await Item.findByIdAndDelete(req.params.id);
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json({ message: 'Item deleted successfully' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Start server
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on http://localhost:${PORT}`);
});