So now that we can store products and fetch all products, let's work on getting a single product. And
for that, we can use our get route here,
this parse is basically an ID which is encoded in the url, if we view the details here, you can see
that url here,
that is the ID as it is stored in mongodb and therefore, we can use that ID to fetch our product of
course.
Hence what I want to do here is I'll reuse my code here with find to find that product and replace
that dummy code here with that code,
however I'll not use find but find one because of course, I know that I will only find one product here
for a given ID but that is a filter which I need to add here.
Now I want to search for ID being equal to that ID and for that, I need to get access to the objectid
object so I'll name that constant objectid and import it from mongodb, object ID.
So just as I created a decimal 128 object, I can also create my own object IDs which mongodb understands.
So now this is stored in this constant and down there,
I can simply use that with the new keyword,
so the objectid is a so-called constructor, a function in Javascript
and there I can pass in a string.
Now that string is basically extractable from the url with the help of express which is the node
framework I'm using here with request params IDs.
So this gives me access to the request parameters,
so the data encoded in the url and then, I'm extracting ID because I named it ID here and that is then
passed to this constructor which gives me an objectid object which mongodb understands.
Find one then returns a promise,
so I have catch and then. In the error case, I'll reuse my error code from down there and simply send an
error response, in the success case I should get my project, my product document and then I can return
this with status code 200 for
I got something and simply pass it as
json data to my frontend,
so now this should be some code that works and allows me to fetch a single product.
If you save all files, you can restart your backend server and now try reloading that page,
now it almost works but I get an issue regarding the number decimal.
Well the problem here is that a single product has its price stored as a decimal, decimal 128 bit and
therefore, I need to convert it,
so I will simply set product doc price equal to product doc price toString, what we already did earlier
just to make sure that this is handled correctly.
After this little addition, we can restart the backend server once again
and now if we reload that front page, we see the product data on the detail page.
So now fetching all products is working, fetching a single product is working, now
of course adding products is working,
now I want to make sure that editing and deleting works too.
So that is what I'll work on next.