Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. const express = require("express"); //import pakietu express
  2. const router = express.Router();
  3. const mongoose = require("mongoose");
  4.  
  5. const Product = require("../models/product");
  6.  
  7. router.get("/", (req,res,next)=>{
  8. Product.find().exec()
  9. .then(docs => {
  10. res.status(200).json(docs);
  11. })
  12. .catch(err => req.status(500).json({error: err}));
  13.  
  14. });
  15. router.post("/", (req,res,next)=>{
  16. const product = new Product({
  17. _id: new mongoose.Types.ObjectId(),
  18. name: req.body.name,
  19. price: req.body.price
  20. });
  21. product.save()
  22. .then(result => {res.status(200).json({
  23. message: "Dodanie nowego produktu",
  24. createdProduct: product
  25. });
  26. })
  27. .catch(err => req.status(500).json({error: err}));
  28. });
  29. router.get("/:productId", (req,res,next)=>{
  30. const id = req.params.productId;
  31. Product.findById(id).exec().then(doc => {
  32. res.status(200).json(doc)
  33. }).catch(err => req.status(500).json({error: err}));
  34.  
  35. })
  36. router.patch("/:productId", (req,res,next)=>{
  37. const id = req.params.productId;
  38. Product.update({_id: id}), {$set:{
  39. name: req.body.name,
  40. price: req.body.price
  41. }}.exec()
  42. .then(res.status(200).json({
  43. message: "Szczegóły produktu o nr " + id
  44. }))
  45. .catch(err => req.status(500).json({error: err}));
  46. })
  47. router.delete("/:productId", (req,res,next)=>{
  48. const id = req.params.productId;
  49. Product.remove({_id: id}).exec()
  50. .then(result => res.status(200).json({
  51. message: "Usunięcie produktu o nr " + id
  52. }))
  53. .catch(err => req.status(500).json({error: err}));
  54. })
  55.  
  56.  
  57. module.exports = router;
  58.  
  59.  
  60. // dorobić orders!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  61. // get, post
  62. // parametryczny: get, delete
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement