-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
97 lines (86 loc) · 2.53 KB
/
server.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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
app.use(express.static(path.join(__dirname, '/dist')));
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/jewelry');
var ProductSchema = new mongoose.Schema({
name: {type: String, minlength: 3},
price: {type: String, minlength: 1},
description: {type: String, required: true},
pic: {type: String, required:true}
})
mongoose.model('Product', ProductSchema);
var Product = mongoose.model('Product');
var UserSchema = new mongoose.Schema({
username: {type: String, minlength: 3},
email: {type: String, minlength: 1},
password: {type: String, required: true}
})
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
//route to create new products
app.post('/api/newProduct', (req,res)=>{
var newProduct = new Product({name: req.body.name, price: req.body.price, description: req.body.description, pic: req.body.pic});
newProduct.save(function(err){
if(err){
res.json(err);
}else{
console.log("object created")
res.json(newProduct);
}
})
})
//get all products
app.get('/api/products', (req,res)=>{
Product.find({}, (err, foundProducts)=>{
if (err) {
res.json(err);
} else {
res.json(foundProducts);
}
})
})
//get one product
app.get('/api/products/:id', (req,res)=>{
Product.findOne({_id: req.params.id}, (err, foundProduct)=>{
if (err) {
res.json(err);
} else {
res.json(foundProduct);
}
})
})
//edit a product
app.put('/api/products/:id', (req,res)=>{
Product.findOne({ _id: req.params.id }, (err, foundProduct) => {
if (err) {
res.json(err);
} else {
foundProduct.name = req.body.name;
foundProduct.price = req.body.price;
foundProduct.pic = req.body.pic;
foundProduct.save((err)=>{
if(err){
res.json(err);
}else{
res.json(foundProduct);
}
})
}
})
})
//remove a product
app.delete('/api/products/:id', (req,res)=>{
Product.remove({_id: req.params.id}, (err)=>{
res.json({message: 'product deleted'});
})
})
app.all("*", (req, res, next) => {
res.sendFile(path.resolve("./dist/index.html"))
});
app.listen(8000, ()=>{
console.log('listening on port 8000');
});