-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
167 lines (138 loc) · 5.75 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
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
const express = require("express");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 5000;
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config();
// Middleware
app.use(cors());
app.use(express.json());
// console.log(process.env.DB_USER);
// console.log(process.env.DB_PASS);
// For Connecting this server with MongoDB Database
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@clustertoymarketplaceju.tv6wggn.mongodb.net/?retryWrites=true&w=majority`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
const addedToyCollection = client.db("toyMarket").collection("addedToys");
/*
The Search Codes are commented for the clash with vercel. These codes are finely work with my local server for the 'All Toys Page' of my app
*/
// Creating index on the 'Toy Name' Field
// const indexKeys = { toyName: 1 };
// const indexOptions = { name: "toyNameSearch" };
// const result = await addedToyCollection.createIndex(indexKeys, indexOptions);
// Searching in All Toys Page in Client-side
app.get("/toySearchByName/:text", async (req, res) => {
const searchText = req.params.text;
const result = await addedToyCollection.find({
$or: [
{ toyName: { $regex: searchText, $options: "i" } }
]
}).toArray();
res.send(result);
});
// For Getting the first 20 data from MongoDB Database Collection
app.get("/toys", async (req, res) => {
const result = await addedToyCollection.find().limit(20).toArray();
res.send(result);
});
// Sorting All Toys as ascending as their price
app.get("/toys/:text", async (req, res) => {
console.log(req.params.text);
if (req.params.text == "ascending") {
const result = await addedToyCollection
.find({}).sort({ price: 1 }).limit(20).toArray();
res.send(result);
}
else {
const result = await addedToyCollection
.find({}).sort({ price: -1 }).limit(20).toArray();
res.send(result);
}
});
// User Specific data showing to the client-side from the server side & 'MongoDB' database
app.get("/toys", async (req, res) => {
// console.log(req.query.email);
let query = {};
if (req.query?.email) {
query = { email: req.query.email }
}
const result = await addedToyCollection.find(query).toArray();
res.send(result);
});
// To get single toy item data, it will also help to update a toy data
app.get("/toys/:id", async (req, res) => {
const id = req.params.id;
// console.log(id);
const query = { _id: new ObjectId(id) };
const result = await addedToyCollection.findOne(query);
res.send(result);
});
// To get toys by their sub-category name through the tab
app.get("/allToysBySubCategory/:subcategory", async (req, res) => {
console.log(req.params.id);
const toys = await addedToyCollection
.find({
subCategory: req.params.subcategory,
}).toArray();
res.send(toys);
});
// Sending & Storing data to 'MongoDB' database via server from the client-side
app.post("/toys", async (req, res) => {
const addToy = req.body;
console.log(addToy);
const result = await addedToyCollection.insertOne(addToy);
res.send(result);
});
// Updating of a single toy item - API
app.put("/toys/:id", async (req, res) => {
const id = req.params.id;
console.log(id);
const updatedToy = req.body;
console.log(updatedToy);
const filter = { _id: new ObjectId(id) };
const options = { upsert: true };
const toy = {
$set: {
price: updatedToy.price,
quantity: updatedToy.quantity,
description: updatedToy.description
}
};
const result = await addedToyCollection.updateOne(filter, toy, options);
res.send(result);
});
// Deleting a single item from collection - API
app.delete("/toys/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await addedToyCollection.deleteOne(query);
res.send(result);
});
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
// Server data getting test code
app.get("/", (req, res) => {
res.send("'Toy Marketplace' App is running");
});
// App is running on server or not - checking the console code for DEVOPS
app.listen(port, () => {
console.log(`'Toy Marketplace' App is listening & running on the port: ${port}`);
});