Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. const express = require('express');
  2. const router = express.Router();
  3. const mongoose = require('mongoose');
  4.  
  5. const Product = require('../models/product');
  6.  
  7.  
  8. router.post('/',(req, res, next) => {
  9.  
  10. const newProduct = new Product({
  11. _id: new mongoose.Types.ObjectId(),
  12. name: req.body.name,
  13. price: req.body.price
  14. });
  15.  
  16. newProduct
  17. .save()
  18. .then(result => {
  19. console.log(result);
  20.  
  21. res.status(200).json({
  22. message:'Harzndling POST requets /products',
  23. createdProduct: result
  24. });
  25.  
  26. })
  27. .catch(err => {
  28. console.log(err);
  29. res.status(500).json({
  30. error: err
  31. });
  32. });
  33.  
  34.  
  35. });
  36.  
  37. router.get('/:productId',(req, res, next) => {
  38. const id = req.params.productId;
  39. Product.findById(id)
  40. .exec()
  41. .then(
  42. doc => {console.log(doc);
  43. if (doc != null) {
  44. res.status(200).json(doc);
  45. } else {
  46. res.status(404).json({
  47. error: 'Not a valid ID'
  48. })
  49. }
  50. })
  51. .catch(err => {
  52. console.log(err);
  53. res.status(500).json({
  54. error: err
  55. })
  56. });
  57. });
  58.  
  59.  
  60.  
  61. router.get('/',(req,res,next) => {
  62. Product.find()
  63. .exec()
  64. .then(docs => {
  65. console.log(docs);
  66. res.status(200).json({
  67. message: 'Getting all products',
  68. products: docs
  69. })
  70. })
  71. .catch(err => {
  72. console.log(err);
  73. res.status(500).json({
  74. error: err
  75. })
  76. })
  77. });
  78.  
  79.  
  80. router.delete('/:productId',(req,res,next) => {
  81. const id = req.params.productId;
  82. Product
  83. .remove({_id:id})
  84. .exec()
  85. .then(result => {
  86. console.log(result);
  87. res.status(200).json({
  88. message: result
  89. })
  90. })
  91. .catch(err => {
  92. console.log(err);
  93. res.status(500).json({
  94. error: err
  95. })
  96. })
  97.  
  98. })
  99.  
  100. router.patch('/:productId',(req,res,next) => {
  101. const id = req.params.productId;
  102. Product
  103. .update({_id:id}, {$set: {name: req.body.newName, price: req.body.newPrice}})
  104. .exec()
  105. .then(result => {
  106. console.log(result);
  107. res.status(200).json({
  108. message: result
  109. })
  110. })
  111. .catch(err => {
  112. console.log(err);
  113. res.status(500).json({
  114. error: err
  115. })
  116. })
  117.  
  118. })
  119.  
  120.  
  121.  
  122.  
  123.  
  124. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement