-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (47 loc) · 1.38 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
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
const UserModel = require("./model/Users.js");
app.use(express.json());
app.use(cors());
app.post("/createUser", async (req, res) => {
const user = req.body;
const newUser = new UserModel(user);
await newUser.save()
res.json(user)
})
app.get("/getUsers", (request, response) => {
UserModel.find({}, (err, result) => {
if (!err) {
response.json(result)
} else {
response.json(err)
}
})
});
app.put("/updateUser", (req, res) => {
const { id, name, age } = req.body
try {
UserModel.findById(id, (err, user) => {
console.log(user)
user.name = name
user.age = age
user.save()
res.send("User has been successfully updated in DB")
})
}
catch (err) {
res.send("Getting error from server")
}
});
app.delete("/deleteUser/:id", async (req, res) => {
const id = req.params.id
await UserModel.findByIdAndRemove(id).exec()
res.send("User has been successfully deleted from DB")
})
mongoose.connect("mongodb+srv://user:[email protected]/Crud?retryWrites=true&w=majority");
const port = process.env.PORT || 8000;
app.listen(port,()=>{
console.log("server is running")
})