-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (61 loc) · 1.75 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 bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// Load environment variables
dotenv.config({path: './config/config.env'});
// Initialize the app
const app = express();
//Initializing host and port number
//const Port = 3000;
const host = 'localhost';
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Connect to the database
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define the expense schema
const expenseSchema = new mongoose.Schema({
title: String,
amount: Number,
});
// Define the expense model
const Expense = mongoose.model('Expense', expenseSchema);
// Define the routes
app.get('/expenses', async (req, res, next) => {
try {
const expenses = await Expense.find();
res.json(expenses);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/expenses', async (req, res, next) => {
try {
const expense = new Expense(req.body);
await expense.save();
res.json(expense);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.delete('/expenses/:id', async (req, res, next) => {
try {
const { id } = req.params;
const expense = await Expense.findById(id);
if (!expense) throw new Error('Expense not found');
await expense.remove();
res.json({ message: 'Expense deleted' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});