0

Here is the code--

router.put('/:id', (req, res) => {
  // update product data
  Product.update(req.body, {
    where: {
      id: req.params.id,
    },
  })
    .then((product) => {
      // find all associated tags from ProductTag
      return ProductTag.findAll({ where: { product_id: req.params.id } });
    })
    .then((productTags) => {
      // get list of current tag_ids
      const productTagIds = productTags.map(({ tag_id }) => tag_id);
      // create filtered list of new tag_ids
      const newProductTags = req.body.tagIds
        .filter((tag_id) => !productTagIds.includes(tag_id))
        .map((tag_id) => {
          return {
            product_id: req.params.id,
            tag_id,
          };
        });
      // figure out which ones to remove
      const productTagsToRemove = productTags
        .filter(({ tag_id }) => !req.body.tagIds.includes(tag_id))
        .map(({ id }) => id);

      // run both actions
      return Promise.all([
        ProductTag.destroy({ where: { id: productTagsToRemove } }),
        ProductTag.bulkCreate(newProductTags),
      ]);
    })
    .then((updatedProductTags) => res.json(updatedProductTags))
    .catch((err) => {
      // console.log(err);
      res.status(400).json(err);
    });
});

enter image description here

this is the json object i tried to use

{
    "id": 1,
    "tag_name": "hat",
    "products": [
        {
            "id": 1,
            "product_name": "Branded Baseball Hat",
            "price": 22.99,
            "stock": 12,
            "category_id": 4,
            "product_tag": {
                "id": 5,
                "product_id": 1,
                "tag_id": 1
            }
        }
    ]
}

I am not sure if i am making the mistake in insomnia when i am trying to test, or if it is in my actual visual studio code. All of my other route tests work. (GET, DELETE, AND POST)

0 Answers0