-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (42 loc) · 1.12 KB
/
server.js
File metadata and controls
51 lines (42 loc) · 1.12 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
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/crudapi', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define a simple schema and model for demonstration
const itemSchema = new mongoose.Schema({
name: String,
quantity: Number,
});
const Item = mongoose.model('Item', itemSchema);
// CRUD operations
// Create
app.post('/items', async (req, res) => {
const item = new Item(req.body);
await item.save();
res.status(201).send(item);
});
// Read
app.get('/items', async (req, res) => {
const items = await Item.find();
res.send(items);
});
// Update
app.put('/items/:id', async (req, res) => {
const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(item);
});
// Delete
app.delete('/items/:id', async (req, res) => {
await Item.findByIdAndDelete(req.params.id);
res.status(204).send();
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});