如何填充嵌套数据对象?

时间:2019-04-29 08:50:21

标签: node.js mongodb mongoose

我现在在Proreg(产品重新注册的简称)模型中有一个嵌套数据(数组中),现在在检索这些属性的实际名称时遇到问题。我用填充方法尝试过,但是没有任何效果,有人可以在这里帮忙吗?

注意:oem将是公司名称,类别将是类别,子类别将是子类别。我只需要填充这三个。

//ProReg Routes

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

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

// @route   GET api/posts/test
// @desc    Tests post route
// @access  Public
router.get("/test", (req, res) => res.json({ msg: "ProReg Works" }));

// @route   GET api/posts
// @desc    Get posts
// @access  Public
router.get("/", (req, res) => {
  ProReg.find()
    .populate('customer', 'customername')
    .populate('customertype', 'customertype')
    .populate('department', 'department')
    .populate({path: 'products', poplate: })
    .sort({ date: -1 })
    .then(proreg => res.json(proreg))
    .catch(err => res.status(404).json({ msg: "No Pro Reg found" }));
});

// @route   GET api/posts/:id
// @desc    Get post by id
// @access  Public
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" })
    );
});

// // @route   POST api/posts
// // @desc    Create post
// // @access  Private
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 using their ids
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 " })
    );
});

// @route   POST /product/:id
// @desc    Add Product to post
// @access  Private
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 product array
      proreg.products.push(newProduct);

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

//Edit a particular Product Registration data using id to edit
router.get("/edit/:id", (req, res) => {
  ProReg.findById(req.params.id)
    .exec()
    .then(proreg => res.json(proreg))
    .catch(err =>
      res.status(404).json({ msg: "Product Registration Not Found" })
    );
});

//Update Product Registration  using their ids
router.post("/update/:id", (req, res) => {
  ProReg.findByIdAndUpdate(req.params.id, req.body)
    .then(proreg => {
      res
        .status(200)
        .json({ msg: "Product Registration Updated Successfully" });
    })
    .catch(proreg => {
      res.status(400).json({ msg: "Error in updating Product Registration " });
    });
});

// @route   DELETE /product/:id/:product_id
// @desc    Remove product from post
// @access  Private
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" })
    );
});

// @route   UPDATE /product/:id/:product_id
// @desc    Remove product from post
// @access  Private
router.post("/product/:id/:product_id", (req, res) => {
  let updateObj = { $set: {} };
  for (var param in req.body) {
    updateObj.$set["products.$." + param] = req.body[param];
  }
  ProReg.update(
    { "products._id": req.params.product_id },
    {
      $set: {
        "products.$.oem": req.body.companyid,
        "products.$.category": req.body.productcategoryid,
        "products.$.subcategory": req.body.productsubcategoryid,
        "products.$.modelno": req.body.modelno,
        "products.$.serialno": req.body.serialno,
        "products.$.warrantyfrom": req.body.warrantyfrom,
        "products.$.warrantyto": req.body.warrantyto,
        "products.$.oemwarrantyfrom": req.body.oemwarrantyfrom,
        "products.$.oemwarrantyto": req.body.oemwarrantyto
      }
    },
    (err, result) => {
      if (err) {
        res.status(500).json({ error: "Unable to update competitor." });
      } else {
        res
          .status(200)
          .json({
            msg:
              "Yes Bakor! You have successfully updated the nnested Product in this Product Regitration Schema"
          });
      }
    }
  );
});

module.exports = router;

//ProReg Model

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
      },
      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);


0 个答案:

没有答案