0

I'm fairly new to nodejs and I'm doing a full stack developer challenge from devchallenges.io (Shoppingify). Below, I'm trying to add a new item. However, there's a slight delay between the return value from the request and the actual value in the database. The value updates straight away which is great however, the return value in the request is the previous value rather than being the current quantity value in the database.

// @route    POST api/category
// @desc     Add category and items
// @access   Private
router.post(
  '/',
  [
    check('name', 'Name is required').notEmpty(),
    check('category', 'Category is required').notEmpty(),
  ],
  auth,
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array(),
      });
    }

    const { name, note, image, category } = req.body;

    const itemObject = { name, note, image, category };

    try {
      const categoryItem = await Category.find({
        user: req.user.id,
      });
      //   check if category object are empty
      if (categoryItem.length === 0) {
        const newCat = new Category({
          user: req.user.id,
          name: category,
          items: itemObject,
        });
        await newCat.save();
        res.json(categoryItem);
      } else if (categoryItem.length !== 0) {
        //   check if category name already exists
        categoryItem.map(async (cat) => {
          if (cat.name.toLowerCase() === category.toLowerCase()) {
            cat.items.push(itemObject);
            await cat.save();
            res.json(categoryItem);
          } else {
            //   create new category
            const newCat = new Category({
              user: req.user.id,
              name: category,
              items: itemObject,
            });
            await newCat.save();
            res.json(categoryItem);
          }
        });
      }
    } catch (error) {
      console.error(error.message);
      res.status(500).send('Server Error');
    }
  }
);

1 Answer 1

0

You are not returning the correct item…

Return the result of newcat.save()

Or try a new findById if newCat is not the correct object to return

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.