Can't add new product to mongodb, having POST 500 error

Viewed 356

I'm having trouble on how adding new product to mongodb. I've done the registration side and it's working fine, and so as login. but when I'm adding product I received this message>

POST http://localhost:5000/api/product/newProduct 500 (Internal Server Error)

I double-check my endpoint and I think im right.

dashboard.jsx
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router'

function Dashboard() {
    const [name, setName] = useState("")
    const [categories, setCat] = useState("")
    const [error, seterror] = useState(false)
    const [data, setData] = useState({})
    const navigate = useNavigate()
    const [price, setprice] = useState(0)

    const handleCat = (e) => {
      setCat(e.target.value.split(','))
    }


    const handleSubmit = async (e) =>{
      e.preventDefault()
      console.log(categories,name,price)
        seterror(false)
        try {
          const prod = await axios.post('http://localhost:5000/api/product/newProduct', {
          name, 
          categories,
          price
          })
          prod.data && navigate('/dashboard')
        } catch (error) {
          seterror(true)
        }
    }
    useEffect(() =>{
      const getProduct = async () =>{
        try {
          const res = await axios.get('http://localhost:5000/api/product')
          setData(res.data)
        } catch (error) {
          
        }
      }
      getProduct()
    },[])

    //console.log(data)

    return (
        <form action="" onSubmit={(e) => handleSubmit(e)}>
        <div>
            <div className="addProductItem">
          <label>Title</label>
          <input
            name="title"
            type="text"
            placeholder="Apple Airpods"
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="addProductItem">
          <label>Description</label>
          <input
            name="desc"
            type="text"
            placeholder="description..."
            onChange={handleCat}
          />
        </div>
        <div className="addProductItem">
          <label>Price</label>
          <input
            name="price"
            type="number"
            placeholder="100"
            onChange={(e) => setprice(e.target.value)}
          />
          <button >Submit</button>
        </div>
        </div>
        </form>
       
    )
}

export default Dashboard

index.js

const express = require('express')
const mongoose = require('mongoose')
const app = express()
const cors = require('cors')
const dotenv = require('dotenv')
const userRoute = require('./routes/auth')
const productRoute = require('./routes/product')

dotenv.config()

app.use(cors())
app.use(express.json())

mongoose
  .connect(process.env.MONGO_DB)
  .then(() => {
    console.log('Connected to Server')
  })
  .catch((err) => console.log(err))

app.use('/api/auth', userRoute)
app.use('/api/product', productRoute)

app.listen(5000, () => {
  console.log('Local Host is Running 5000')
})

productRoute.js

const router = require('express').Router()
const Product = require('../models/Product')

router.post('/newProduct', async (req, res) => {
  const newProduct = new Product(req.body)

  try {
    const savedProduct = await newProduct.save()
    res.status(200).json(savedProduct)
  } catch (error) {
    res.status(500).json(error)
  }
})


router.get('/', async (req, res) => {
  try {
    const products = await Product.find()
    res.status(200).json(products)
  } catch (error) {
    res.status(500).json(error)
  }
})
module.exports = router

schema

const mongoose = require('mongoose')
const ProductSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, unique: true },
    price: { type: Number, required: true },
    categories: { type: Array },
    img: { type: String },
  },
  { timestamps: true }
)

module.exports = mongoose.model('Product', ProductSchema)
1 Answers

Referencing your product Schema

const ProductSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, unique: true },
    price: { type: Number, required: true },
    categories: { type: Array },
    img: { type: String },
  },
  { timestamps: true }
)

Here categories is defined as type array and you are sending categories as string from frontend referencing your frontend code

const [categories, setCat] = useState("")

const prod = await axios.post('http://localhost:5000/api/product/newProduct', { name, categories, price })

changing your schema categories type to string would solve the problem or you should send an array of categories to backend

Related