Home > Back-end >  nodejs mongodb object id to string fontend
nodejs mongodb object id to string fontend

Time:11-18

Mongo

I can't get data from mongo because ID is ObjectID. I want to convert it to string. I can't get data from mongo because ID is ObjectID , I want to convert it to string

enter code here

const SingleProduct = () => {
    const {id} = useParams();
    const [data, setData] = useState([]);
    // const [filter, setFilter] = useState(data);
    const [loading, setLoading] = useState(false);
    let componentMounted = false;



    useEffect(() => {
        const getProducts = async () => {
            setLoading(true);
            // Link database product
            const response = await fetch(`http://localhost:8000/api/products/${id}`);
            setData(await response.json());
            setLoading(false);
        }
        getProducts();
    }, []);

CodePudding user response:

In your frontend/src/components/products/Products/Products.jsx file you should probably pass the _id of the item to the Item component:

return (
  <>
    {data.map((item, index) => {
      return (
        <Item
          id={item._id} // Here pass the ObjectId of the item, since `id` is not defined
          img={item.image}
          title={item.title}
          desc={item.desc}
          price={item.price}
          item={item}
          key={index}
        />
      );
    })}
  </>
);
  • Related