新产品保存在猫鼬数据库中,但它显示该产品尚未创建

问题描述 投票:0回答:1
router.post('/', authenticateToken,isAdmin, async (req, res) => {
    try{
        const category = await Category.findById(req.body.category)
        if (!category) return res.status(400).send('Invalid Category')

        const product = new Product({
            name: req.body.name,
            description: req.body.description,
            size: req.body.size,
            image: req.body.image,
            images: req.body.images,
            category: req.body.category,
            countInstock: req.body.countInstock,
            price: req.body.price,
            rating: req.body.rating,
            isFeatured: req.body.isFeatured,
            dateCreated: req.body.dateCreated,
        })
        product = await product.save();
    } catch(error){
        return res.status(500).send("The product is not created")

    }

    res.send(product)
})

产品保存在 mongoose db 数据库中,但也没有返回产品详细信息,而是显示消息“产品未创建”

node.js mongoose async-await try-catch mongoose-schema
1个回答
0
投票
    router.post('/', authenticateToken, isAdmin, async (req, res) => {
    try {
        const category = await Category.findById(req.body.category);
        if (!category) return res.status(400).send('Invalid Category');

        const product = new Product({
            name: req.body.name,
            description: req.body.description,
            size: req.body.size,
            image: req.body.image,
            images: req.body.images,
            category: req.body.category,
            countInstock: req.body.countInstock,
            price: req.body.price,
            rating: req.body.rating,
            isFeatured: req.body.isFeatured,
            dateCreated: req.body.dateCreated,
        });

        const savedProduct = await product.save(); // Save the product in another variable as you cannot reassign a const variable in JavaScript.
        res.send(savedProduct); // Send the saved product details
    } catch (error) {
        console.error(error); // Log the error for debugging
        return res.status(500).send("The product is not created")// You are getting this message because you are getting an error or exception. Check the exception.

    }
});
© www.soinside.com 2019 - 2024. All rights reserved.