new product get saved in the mongoose db but its shows that the product is not created

22 Views Asked by At
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)
})

The product is saved in mongoose db database but then also instead of returning the product details it gives the message "The product is not created"

1

There are 1 best solutions below

0
Arijit Sarkar On BEST ANSWER
    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 error data.

    }
});