API
Fetch By Slug

Fetching Product by Slug

Get Slug

I need to first find a way to access slug (let's say is we want to get superbook-pro product) in URL
( localhost:3000/Product/superbook-pro ), then i can find the requested product. URL Sample

Context

Context is an object used to carry important details like request parameters, headers, and authentication data.
Here, i use context.params.slug to access the 'slug' parameter from the URL

API.js
async function FetchOneProduct(context) {
  const { params } = context;
  const { slug } = params;
  await db.connect();
  const product = await Product.findOne({ slug }).lean();
  await db.disconnect();
  return {
    props: {
      product: product ? db.convertDocOptToObj(product) : null,
    },
  };
}

Find Product

After connecting to Database is time to fetch
line5: fetch a single product

line7: If product exists in database, db.convertDocOptToObj converts the left properties (id , createdAt , updatedAt) to plain JavaScript objects.
then returns products as props to make it available for ProductScreen components to handle