-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (83 loc) · 2.36 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
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
mongoose.connect('mongodb://localhost:27017/CRUD').then(console.log('db connected'))
const app = express();
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: false }))
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number
})
const Product = new mongoose.model('product', productSchema)
// create product api
app.post('/api/v1/product/new', async (req, res) => {
const product = await Product.create(req.body);
res.status(200).json({
success: true,
product
})
})
//Read product api
app.get('/api/v1/product', async (req, res) => {
const products = await Product.find()
res.status(200).json({
success: true,
products
})
})
//Update product api
app.put('/api/v1/product/:id', async (req, res) => {
try {
let product = await Product.findById(req.params.id)
if (!product) {
return res.status(404).json({
success: false,
message: "Product not found"
});
}
product = await Product.findByIdAndUpdate(req.params.id, req.body, {
new: true,
useFindAndModify: false,
runValidators: true
})
res.status(200).json({
success: true,
message: "product updated successfully",
product
})
} catch (error) {
res.status(500).json({
success: false,
message: "internal server error"
})
}
})
//Delete product api
app.delete('/api/v1/product/:id', async (req, res) => {
try {
const id = req.params.id;
const product = await Product.findOne({ _id: id });
if (!product) {
return res.status(404).json({
success: false,
message: "Product not found"
});
}
await Product.findByIdAndDelete(id);
res.status(200).json({
success: true,
message: "Product deleted successfully",
product
});
} catch (error) {
res.status(500).json({
success: false,
message: "Internal Server Error"
});
}
});
app.listen(4000, () => {
console.log('server is running')
})