-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathtest.js
262 lines (232 loc) · 7.21 KB
/
test.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
const express = require("express");
const cors = require("cors");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const jwt = require("jsonwebtoken"); // import jwt if use JsonWeb token
require("dotenv").config(); // import env file if use environment variables after install || npm install dotenv --save|| ane Create a .env file in the root of your project:
const port = process.env.PORT || 5000;
const app = express();
// used Middleware
app.use(cors());
app.use(express.json());
// Connact With MongoDb Database
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.krxly.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
// Create a async fucntion to all others activity
async function run() {
try {
await client.connect();
// Create Database to store Data
const testCollection = client.db("testDatabaseName").collection("testData");
// Get/Access all data from mongodb database
// Server Site Code
app.get("/service", async (req, res) => {
const result = await testCollection.find().toArray();
res.send(users);
});
// Client site code
useEffect(() => {
fetch("http://localhost:5000/service")
.then((res) => res.json())
.then((data) => console.log(data));
}, []);
// Get/Access Spacific data from mongodb database with id/email
// Server Site Code
app.get("/service/:id", async (req, res) => {
const id = req.params.id;
const result = await testCollection.find({ _id: ObjectId(id) }).toArray();
res.send(result);
});
// Client site code
useEffect(() => {
fetch(`http://localhost:5000/service/${id}`)
.then((res) => res.json())
.then((data) => console.log(data));
}, []);
// Get/Access Spacific data from mongodb database with multiple query
// Server Site Code
app.get("/service", async (req, res) => {
const query = req.body;
const result = await testCollection.find(query).toArray();
res.send(result);
});
// Client site code
const query = {
email: "exampale@example.com",
name: "set name",
time: "set time",
};
useEffect(() => {
fetch("http://localhost:5000/service", {
method: "GET",
body: JSON.stringify(query), // send any of query by which you find data
})
.then((res) => res.json())
.then((data) => console.log(data));
}, []);
// Get/Access Limited data from mongodb database after find with query
// Server Site Code
app.get("/service", async (req, res) => {
const query = {};
const findData = testCollection.find(query);
const result = await findData.skip(5).limit(3).toArray(); //you can also set skip & limit range dynamicly.
res.send(result);
});
// Client site code
useEffect(() => {
fetch("http://localhost:5000/service")
.then((res) => res.json())
.then((data) => console.log(data));
}, []);
// Post API
// Post data without cheack on mongodb database
// Server Site Code
app.post("/service", async (req, res) => {
const service = req.body;
const result = await testCollection.insertOne(service);
res.send(result);
});
// Client site code
const newData = {
// stroe new Data in Object here
name: "",
price: "",
};
fetch("http://localhost:5000/service", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(newData),
})
.then((res) => res.json())
.then((result) => {
const allData = [...previusData, newData];
console.log(newReview);
});
// Post data With cheack in mongodb database. Batter to use Put Methood for this task
// Server Site Code
app.post("/service/:email", async (req, res) => {
const service = req.body.service;
const query = req.body.newQuery;
query.email = email;
const exist = testCollection.findOne(query);
if (exist) {
res.send({ result: "success" });
} else {
const result = await testCollection.insertOne(service);
res.send(result);
}
});
// Client Site Code
const service = {
name: "",
price: "",
};
const newQuery = {
name: "",
time: "",
};
fetch("http://localhost:5000/service", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({ service, newQuery }),
})
.then((res) => res.json())
.then((result) => {
const allData = [...previusData, newData];
console.log(newReview);
});
// Put Methood
// Update & insert Data on database by id/email/otherQuery
// Server site Code
app.put("/service/:id", async (req, res) => {
const id = req.params.id;
const service = req.body;
const result = await testCollection.updateOne(
{ _id: ObjectId(id) }, // Find Data by query many time query type is "_id: id" Cheack on database
{
$set: service, // Set updated Data
},
{ upsert: true } // define work
);
res.send({ result });
});
// Client Site Code
const updatedData = {
name: "",
role: "",
};
fetch(`http://localhost:5000/service/${id}`, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(updatedData),
})
.then((res) => res.json())
.then((data) => {
alert("item Updated successfully!!!");
});
// Patch api
// update Data by id/email/othersQueary
// Server site code
app.patch("/service/:id", async (req, res) => {
const id = req.params.id;
const service = req.body;
const result = await testCollection.updateOne(
{ _id: id }, // sometime _id:ObjectId(id)
{
$set: service,
}
);
res.send(result);
});
// Client site code
// const updatedData = {
// name: "",
// role: "",
// };
// fetch(`http://localhost:5000/service/${id}`, {
// method: "patch",
// headers: {
// "content-type": "application/json",
// },
// body: JSON.stringify(updatedData),
// })
// .then((res) => res.json())
// .then((data) => {
// alert("item Updated successfully!!!");
// });
// Delete API
// Delete Data form mongodb Database by id
// Server site code
app.delete("/service/:id", async (req, res) => {
const id = req.params.id;
const result = await testCollection.deleteOne({ _id: ObjectId(id) });
res.send(result);
});
// Client Site Code
fetch(`http://localhost:5000/service/${_id}`, {
method: "DELETE",
})
.then((res) => res.json())
.then((data) => {});
} finally {
// await client.close();
}
}
// Call the fuction you decleare abobe
run().catch(console.dir);
// Root Api to cheack activity
app.get("/", (req, res) => {
res.send("Hello From NR Computers!");
});
app.listen(port, () => {
console.log(`NR Computers listening on port ${port}`);
});