Мне нужно обновить продукты, которые вложены в регистрацию продукта.Я могу сделать удаление, но не могу понять, как редактировать и обновлять - PullRequest
0 голосов
/ 26 апреля 2019

Это маршруты proreg, откуда я вызываю API, маршруты get, add и delete работают отлично, но я не могу обновить также, если честно, я не знаю, как это сделать, я просто следую кодам удаления, гдеЯ фильтровал данные о товарах.Код для редактирования маршрутов находится в последней строке.

const express = require("express");
const router = express.Router();

// Post model
const ProReg = require("../../../models/Entries/ProReg");

//Get Product Registration
router.get("/", (req, res) => {
  ProReg.find()
    .sort({ date: -1 })
    .then(proreg => res.json(proreg))
    .catch(err => res.status(404).json({ msg: "No Pro Reg found" }));
});

//Get a particular data of Product Registration
router.get("/:id", (req, res) => {
  ProReg.findById(req.params.id)
    // .populate({path: 'products', populate:['oem','category'], select:'_id'})
    // .populate('products', 'oem')
    .then(proreg => res.json(proreg))
    .catch(err =>
      res.status(404).json({ msg: "No Pro Reg found with that ID" })
    );
});

//Adding new Product Registration 
router.post("/", (req, res) => {
  const newProReg = new ProReg({
    refno1: req.body.refno1,
    refno2: req.body.refno2,
    date: req.body.date,
    customer: req.body.customerid,
    customertype: req.body.customertypeid,
    department: req.body.customersubdepartmentid
  });

  newProReg.save().then(proreg => res.json(proreg));
});

//Delete particular id of Product Registration Data
router.delete("/delete/:id", (req, res) => {
  ProReg.findById(req.params.id)
    .then(proreg =>
      proreg
        .remove()
        .then(proreg =>
          res.status(200).json({ msg: "Pro Reg Deleted Successfully" })
        )
    )
    .catch(proreg =>
      res.status(400).json({ msg: "Error in deleting Pro Reg " })
    );
});

/** Adding Products through "/product/:id" (:id of Product Regitration created above)*/
router.post("/product/:id", (req, res) => {
  ProReg.findById(req.params.id)
    .then(proreg => {
      const newProduct = {
        oem: req.body.companyid,
        category: req.body.productcategoryid,
        subcategory: req.body.productsubcategoryid,
        modelno: req.body.modelno,
        serialno: req.body.serialno,
        warrantyfrom: req.body.warrantyfrom,
        warrantyto: req.body.warrantyto,
        oemwarrantyfrom: req.body.oemwarrantyfrom,
        oemwarrantyto: req.body.oemwarrantyto
      };
      // Add to comments array
      proreg.products.push(newProduct);

      // Save
      proreg.save().then(proreg => res.json(proreg));
    })
    .catch(err => res.status(404).json({ proregnotfound: "No pro reg found" }));
});


/** Deleting Products through {/product/:id/:product_id"} (:id of Product Regitration created above, and :product_id is of the product)*/

router.delete("/product/:id/:product_id", (req, res) => {
  ProReg.findById(req.params.id)
    .then(proreg => {
      // Check to see if Product exists
      if (
        proreg.products.filter(
          product => product._id.toString() === req.params.product_id
        ).length === 0
      ) {
        return res.status(404).json({ message: "Product does not exist" });
      }

      // Get remove index
      const removeIndex = proreg.products
        .map(item => item._id.toString())
        .indexOf(req.params.product_id);

      // Splice product out of array
      proreg.products.splice(removeIndex, 1);

      proreg.save().then(proreg => res.json(proreg));
    })
    .catch(err =>
      res.status(404).json({ message: "No Product Registration found" })
    );
});

//This is where i want to update the product only this is the code and I am not getting it.


router.post("/product/:id/:product_id", (req, res) => {
  ProReg.findById(req.params.id)
    .then(proreg => {
      // Check to see if Product exists
      if (
        proreg.products.filter(
          product => product._id.toString() === req.params.product_id
        ).length === 0
      ) {
        return res.status(404).json({ message: "Product does not exist" });
      }

      // Get get index
      const getIndex = proreg.products
        .map(item => item._id.toString())
        .indexOf(req.params.product_id);

      proreg.products.update(getIndex, 1);

      proreg.save().then(proreg => res.json(proreg));
    })
    .catch(err =>
      res.status(404).json({ message: "No Product Registration found" })
    );
});


module.exports = router;

Это модель ProReg

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const ProRegSchema = new Schema({

  refno1: {
    type: String
  },
  refno2: {
    type: String
  },
  date: {
    type: Date
  },
  customer: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "customer" 
},
customertype: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "customertype" 
},
department: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "customersubdepartment" 
},

  products: [{
      oem: {
        type: Schema.Types.ObjectId,
        ref: 'product'
      },
      category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "product"
      },
      subcategory: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "product"
      },
      modelno: {
        type: String
      },
      serialno: {
        type: String,
        required: true
      },
      warrantyfrom: {
        type: Date
      },
      warrantyto: {
        type: Date
      },
      oemwarrantyfrom: {
        type: Date
      },
      oemwarrantyto: {
        type: Date
      }, 
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = ProReg = mongoose.model('proreg', ProRegSchema);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...