json 数据延迟 - Node、Express、MongoDB

Delay in json data - Node, Express, MongoDB

我是 nodejs 的新手,我正在 devchallenges.io (Shoppingify) 参加全栈开发人员挑战赛。下面,我正在尝试添加一个新项目。但是,请求中的 return 值与数据库中的实际值之间存在轻微延迟。该值立即更新,这很好,但是,请求中的 return 值是以前的值,而不是数据库中的当前数量值。

// @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');
    }
  }
);

您没有return输入正确的项目……

Return newcat.save()

的结果

如果 newCat 不是 return

的正确对象,则尝试新的 findById