Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require("express");
- const router = express.Router();
- const mongoose = require("mongoose");
- const multer = require("multer");
- const storage = multer.diskStorage({
- destination:function(req, file, cb){
- cb(null, "./uploads/");
- },
- filename: function(req, file, cb){
- cb(null, new Date().toISOString().replace(":","_").replace(":","_") + file.originalname);
- }
- })
- const upload = multer({storage: storage});
- const Product = require("../models/product");
- router.get("/",(req,res,next)=>{
- Product.find().exec()
- .then(docs =>{
- res.status(200).json(docs);
- })
- .catch(err=>res.status(500).json({error:err}));;
- });
- router.post("/", upload.single("productImage"), (req,res,next)=>{
- console.log(req.file);
- const product = new Product({
- _id: new mongoose.Types.ObjectId(),
- name: req.body.name,
- price: req.body.price
- });
- product.save()
- .then(result => {
- res.status(200).json({
- message:"Dodano nowy produkt",
- createdProduct: result
- });
- })
- .catch(err=>res.status(500).json({error:err}));
- });
- router.get("/:productId",(req,res,next)=>{
- const id = req.params.productId;
- Product.findById(id).exec()
- .then(doc => {
- res.status(200).json(doc);
- })
- .catch(err=>res.status(500).json({error:err}));
- });
- router.patch("/:productId",(req,res,next)=>{
- const id = req.params.productId;
- Product.findByIdAndUpdate(id,{$set:{
- name: req.body.newName,
- price: req.body.newPrice
- }}).exec()
- .then(result =>{
- res.status(200).json(result);
- })
- .catch(err=>res.status(500).json({error:err}));
- });
- router.delete("/:productId",(req,res,next)=>{
- const id = req.params.productId;
- Product.findByIdAndRemove(id).exec()
- .then(result =>{
- res.status(200).json({message:"Usunieto produkt o nr: "+id});
- })
- .catch(err=>res.status(500).json({error:err}));
- });
- module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement