-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.js
More file actions
69 lines (56 loc) · 1.74 KB
/
Server.js
File metadata and controls
69 lines (56 loc) · 1.74 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const express = require("express");
const app = express();
require("dotenv").config({path:"./config/.env"});
const mongoose = require("mongoose");
const User = require("./models/User.js");
const bodyParser = require("body-parser");
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// connection to database---------------------------------------
mongoose.connect(process.env.MONGO_URI)
.then(()=>console.log("db connected"))
.catch(err => console.log(err))
//routes--------------------------------------------------------
app.post("/",async (req,res,next)=>{
const newUser = new User(req.body);
try{
await newUser.save();
res.status(201).json({message: "success"})
}catch(error){
res.status(500).send(error);
}
});
app.get("/",async (req,res,next)=>{
try{
const users = await User.find({});
res.status(201).send(users);
}catch(error){
res.status(500).send(error);
}
});
app.put("/:id",async (req,res,next)=>{
try{
const updateUser = await User.findOneAndUpdate(
{_id: req.params.id},
{$set: req.body}
);
if(!updateUser){
res.status(404).send("not found");
}
res.status(201).send(updateUser);
}catch(error){
res.status(500).send(error);
}
});
app.delete("/:id",async (req,res,next)=>{
try{await User.findOneAndDelete({_id:req.params.id})
res.status(201).send("success");}
catch(error){
res.status(500).send(error);
}
});
// run the server-----------------------------------------------
const port = process.env.PORT;
app.listen(port,()=>console.log("SERVER RUN IN PORT ",port));