-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (57 loc) · 1.84 KB
/
server.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
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();
const User = require("./models/User");
let testUsers = require("./utils/test-users");
const app = express();
app.use(express.json());
app.use(cors());
mongoose
.connect(process.env.MONGODB_URI, { useNewUrlParser: true })
.then(() => console.log("MongoDb Connected..."))
.catch(error => console.log(error));
// app.get("/addusers", (req, res) => {
// testUsers().map(userObj => {
// let newUser = User(userObj);
// newUser.save();
// });
// res.send("Adding Users to DB...");
// });
app.get("/users", (req, res) => {
User.find()
.then(users => res.json({ users }))
.catch(error => res.json({ error: "Error while fetching users." }));
});
app.post("/add", (req, res) => {
User.findOne({ email: req.body.user.email }).then(user => {
if (user) {
res.json({ message: "Email already in use." });
} else {
let newUser = User(req.body.user);
newUser
.save()
.then(user => res.json({ user }))
.catch(error => res.json({ error: "Failed to add user." }));
}
});
});
app.post("/delete", (req, res) => {
User.findByIdAndDelete(req.body.id)
.then(user => {
if (user) res.json({ message: "User deleted successfully." });
else res.json({ mesage: "No such user." });
})
.catch(error => res.json({ error: "Could not delete user, try again." }));
});
app.post("/edit", (req, res) => {
User.findByIdAndUpdate(
{ _id: req.body.user.id },
{ $set: req.body.user },
{ new: true }
)
.then(user => res.json({ message: "User info updated." }))
.catch(error => res.json({ error: "Could not update user, try again." }));
});
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server is running on ${port}...`));