-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (35 loc) · 987 Bytes
/
index.js
File metadata and controls
55 lines (35 loc) · 987 Bytes
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
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.use(express.json());
// CONNECT DATABASE
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
// CREATE SCHEMA
const studentSchema = new mongoose.Schema({
name: String,
branch: String,
year: String
});
const Student = mongoose.model("Student", studentSchema);
// ROOT API
app.get("/", (req, res) => {
res.send("Backend + Database working ");
});
// SAVE STUDENT
app.post("/student", async (req, res) => {
const student = new Student(req.body);
await student.save();
res.send(" Student saved to database");
});
// FETCH STUDENTS
app.get("/student", async (req, res) => {
const students = await Student.find();
res.json(students);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});