-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (47 loc) · 1.51 KB
/
Copy pathindex.js
File metadata and controls
55 lines (47 loc) · 1.51 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
// index.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose"); // Import mongoose
const Event = require("./models/Event"); // Import the Event model
const app = express();
app.use(cors());
app.use(express.json());
// MongoDB connection setup with Mongoose
const mongoURI = "mongodb://localhost:27017/finflare"; // Use your database URL
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Connected to MongoDB using Mongoose!");
})
.catch((err) => {
console.error("Error connecting to MongoDB with Mongoose", err);
});
// Define routes
app.get("/", (req, res) => {
res.send("FinFlare Backend Running!");
});
// Get events from MongoDB using Mongoose
app.get("/api/events", (req, res) => {
Event.find() // Mongoose query
.then((events) => {
res.json(events);
})
.catch((err) => {
res.status(500).json({ error: "Failed to fetch events", details: err });
});
});
// Add an event to MongoDB using Mongoose
app.post("/api/events", (req, res) => {
const newEvent = new Event(req.body);
newEvent.save() // Save the new event using Mongoose
.then(() => {
res.status(201).json({ message: "Event added!" });
})
.catch((err) => {
res.status(500).json({ error: "Failed to add event", details: err });
});
});
// Set up the server to listen on a port
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});