-
Notifications
You must be signed in to change notification settings - Fork 0
/
Node Server Setup + Mongodb CRUD Operation.txt
325 lines (267 loc) · 9.88 KB
/
Node Server Setup + Mongodb CRUD Operation.txt
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
https://expressjs.com/en/resources/middleware.html
https://www.mongodb.com/docs/drivers/node/current/usage-examples/
https://zellwk.com/blog/crud-express-mongodb/
> https://testfully.io/blog/postman-api-testing/
🎯 Initial Node Server Setup (express/mongodb)
> create folder structure (backend/frontend)
> npm init -y
> npm i express cors mongodb
> npm install -g nodemon
> create .gitignore > node_modules + .env
> go to package.json
//>
"scripts": {
"start": "node index.js",
"start-dev": "nodemon index.js",
}
> create index.js and open
//>
const express = require("express");
const app = express();
const cors = require("cors");
const { MongoClient, ServerApiVersion } = require("mongodb");
const ObjectID = require('mongodb').ObjectID;
const port = process.env.POST || 5000;
// use middleware
app.use(cors());
app.use(express.json());
// for testing
app.get("/", (req, res) => {
res.send({ message: "Success" });
});
app.listen(port, () => {
console.log("Listening to port", port);
});
> command nodemon index.js [testing conncetion]
🎯 Envarionment Variable Setup
> go to https://northflank.com/guides/connecting-to-a-mongo-db-database-using-node-js
> require('dotenv').config();
> create .env variable
> MONGO_URI=mongo+srv://<user>:<pass>@<host>:<port>/<database>?<connection options>
> Doesnt matter, using
> whitespace between (=)
> string
> not using string
> const uri = process.env.MONGO_URI;
🎯 MongoDB Setup
> signup google access
> create user/pass (copy)
> network access > ip address: allow access from anywhere
> database > connect > copy from include all
> paste in index.js (Server)
> replace with <password>
> comment // client.close() ❌
🎯 Initialize CRUD operation
> paste async run function
> copy from mongodb initial setup connection
> const collection = client.db("database name").collection("collection name");
> const collection = client.db("users").collection("usersCollection");
> console.log("connected mongodb") [testing connection]
> dont forget to call > run().catch(console.dir);
> app.method(endpoint, callback)
> Callback Function ✔
(req, res)
> req
> client থেকে request receive করে।
> req.body
> req.body is actually key value pair json data from POST method (client side)
//>
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
})
> req.query
> query strings from URL
> key value form
> start after (?) mark
> req.params.id
> receive dynamic parameter from URL
> endpoint using with /:id
> endpoint parameter and req.params.parameter need to be same
> require ObjectId and pass idParameter if update based on _id
> res
> request receive করার পর process করে client কে data send করে।
> res.send(result)
> Delete === Get && Post === Post
// GET API (read all notes) ❄❄❄
//>
app.get("/notes", async (req, res) => {
const query = req.query;
const cursor = notesCollection.find(query);
const result = await cursor.toArray();
res.send(result);
});
> go to > [Find Multiple Documents] (https://www.mongodb.com/docs/drivers/node/current/usage-examples/find/#find-multiple-documents)
> we will get all data so endpoint should be plural example: ("/notes")
> get query from req.query
> create cursor, pass query
> convert result as an Array before sending
> send result as a response
> copy and comment endpoint from postman to index.js
// POST API (create a single note) ❄❄❄
//>
app.post("/note", async (req, res) => {
const data = req.body;
console.log(data); // testing
const result = await notesCollection.insertOne(data);
res.send(result)
});
> go to > [Insert a Document] (https://www.mongodb.com/docs/drivers/node/current/usage-examples/insertOne/#insert-a-document)
> we will create a single data so endpoint should be single example: ("/note")
> get receive body data from req.body
> send post request from postman Body > raw > JSON
> console.log(data) for testing post data
> pass data into collection
> send result as a response
> copy and comment endpoint from postman to index.js
// PUT API (update a single note) ❄❄❄
//>
app.put("/note/:id", async (req, res) => {
const id = req.params.id;
const data = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateNote = {
$set: {
userName: data.userName,
textData: data.textData
},
/* modify object using spread operator
$set: {
...data
},
*/
};
const result = await notesCollection.updateOne(filter, updateNote, options);
res.send(result)
});
> go to [Update a Document](https://www.mongodb.com/docs/drivers/node/current/usage-examples/updateOne/#update-a-document)
> use params in endpoint example ("/note/:id")
> get id from req.params.id
> here parameter need to be same example ("/note/:same_parameter" && req.params.same_parameter)
> console.log(id) // testing
> passing id from url using Postman
> http://localhost:5000/note/62659010b03fcf637b79ebdd
> get receive body data from req.body
> console.log(data) // testing
> create a filter for update
> require ObjectId and pass id parameter
> set option upsert: true:
> if not exist add new value or if exist update
> set update object manually or using spread operator example ...data
> updateOne(filter, updateNote, options), parameters need to be placed serially
> send result as a response
> copy and comment endpoint from postman to index.js
> test GET, POST, PUT methods using Postman
// DELETE API (delete a single note) ❄❄❄
//>
app.delete("/note/:id" , async(req, res) =>{
const id = req.params.id;
const filter = { _id: ObjectId(id) };
const result = await notesCollection.deleteOne(filter);
res.send(result);
})
> go to [Delete a Document] (https://www.mongodb.com/docs/drivers/node/current/usage-examples/deleteOne/#delete-a-document)
> get id from req.params.id
> create a filter for delete
> set ObjectId and pass id parameter
> send result as a response
> test GET, POST, PUT, DELETE methods using Postman
> copy and comment endpoint from postman to index.js
🐼 Get all data from MongoDB
//>
const [notes, setNotes] = useState([]);
const [isReload, setIsReload] = useState(false); ✔
useEffect(() => {
// GET Method 🐼
fetch("http://localhost:5000/notes")
.then((res) => res.json())
.then((data) => setNotes(data));
}, [isReload]);
> declare state for notes (all data)
> set isReload as a dependency for reload data after changes
🐼 Search by query parameter from MongoDB and display data setNotes(data)
//>
const handleSearch = (e) => {
e.preventDefault();
const searchText = e.target.searchText.value;
// clear input
e.target.searchText.value = "";
if(searchText === ""){ // load all data when empty
fetch("http://localhost:5000/notes")
.then((res) => res.json())
.then((data) => setNotes(data));
} else{
fetch(`http://localhost:5000/notes?userName=${searchText}`)
.then((res) => res.json())
.then((data) => setNotes(data)); ✔
}
};
> search by query parameter from MongoDB
> display result by setNotes(data) ✔
🐼 Insert new data in MongoDB by POST Method and reload by setIsReload(!isReload)
//>
const handlePost = (e) => {
e.preventDefault();
const userName = e.target.userName.value;
const textData = e.target.textData.value;
// clear input
e.target.userName.value = "";
e.target.textData.value = "";
fetch("http://localhost:5000/note", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({ userName, textData }),
/* body:JSON.stringify({
"userName": userName,
"textData": textData
}) */
}).then((res) => res.json());
// .then((data) => console.log(data));
setIsReload(!isReload); ✔
};
> insert new data by POST Method
> body set by manually or object literal also using spread operator at backend
> reload by setIsReload(!isReload) ✔
> here isReload fetch all data after changes
🐼 Delete data from MongoDB using DELETE Method and reload by setIsReload(!isReload)
//>
const handleDelete = (id) => {
fetch(`http://localhost:5000/note/${id}`, {
method: "DELETE",
});
setIsReload(!isReload);
};
> delete data from MongoDB using DELETE Method
> reload by setIsReload(!isReload) ✔
> here isReload fetch all data after changes
🐼 Update data using PUT Method and reload by setIsReload(!isReload)
//>
const handleUpdate = (e) => {
e.preventDefault();
const userName = e.target.userName.value;
const textData = e.target.textData.value;
// clear input
e.target.userName.value = "";
e.target.textData.value = "";
fetch(`http://localhost:5000/note/${id}`, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({ userName, textData }),
/* body:JSON.stringify({
"userName": userName,
"textData": textData
}) */
}).then((res) => res.json());
// .then((data) => console.log(data));
setIsReload(!isReload); ✔
};
> Update data using PUT Method
> reload by setIsReload(!isReload) ✔
> here isReload fetch all data after changes
> create custom hook is optional for [isReload, setIsReload]