[英]Passing json data from mongodb query to javascript variable client side using express and node
[英]Delay in json data - Node, Express, MongoDB
我對 nodejs 還很陌生,我正在做來自 devchallenges.io (Shoppingify) 的全棧開發者挑戰。 下面,我正在嘗試添加一個新項目。 但是,請求的返回值與數據庫中的實際值之間存在輕微延遲。 值立即更新,這很好,但是請求中的返回值是以前的值,而不是數據庫中的當前數量值。
// @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');
}
}
);
您沒有返回正確的項目...
返回 newcat.save() 的結果
或者如果 newCat 不是要返回的正確對象,請嘗試新的 findById
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.