Soy bastante nuevo en nodejs y estoy haciendo un desafío de desarrollador de pila completa de devchallenges.io (Shoppingify). A continuación, estoy tratando de agregar un nuevo elemento. Sin embargo, hay un ligero retraso entre el valor de retorno de la solicitud y el valor real en la base de datos. El valor se actualiza de inmediato, lo cual es excelente; sin embargo, el valor devuelto en la solicitud es el valor anterior en lugar de ser el valor de cantidad actual en la base de datos.
// @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'); } } );No está devolviendo el artículo correcto...
Devuelve el resultado de newcat.save()
O intente un nuevo findById si newCat no es el objeto correcto para devolver