To add a comment, we will update this array with a push operator with the request body as the new comment.
The route uses the collection.updateOne() method with the unique id specified as an ObjectId, and the operator as the second argument.
And last but not least, we need to handle the delete request. The users will have the ability to delete an article from our blog.
Here, we are using a parametrized route to get the id of the object to delete. The post is then deleted with the collection.deleteOne() method.
Your server is now ready to be used. You can already test it with tools such as Postman or curl. For example, you could run the following command to get the latest articles.
Now, any third-party applications can connect to this server, but let's see how we can get our React application to connect.
Setting up the front end
Plenty of tutorials provide a lot more detail on how to query a public API and manage responses from a client request. Understanding the basics of React applications is out of the scope of this article, but you can see examples of how to access the API you just created in the /app/src folder.
In the /app/src/pages/Home.js file, we retrieve the latest three entries from the blog. This is done through a request to the /posts/latest route of the server. In this application, we are using the browser's native fetch object.
All requests to read from the API follow the same pattern. We use the following to fetch all the articles in the app/src/pages/Archive.js page.
The only difference here is the route. The same goes for fetching a single document in app/src/pages/Post.js.
We still use the fetch object to create a new entry, but you will need to specify the HTTP method, an additional http header, and the request body. The code to create, update, or delete entries can be found in /app/src/pages/Create.js.
Doing an update follows the same patterns but with a different method.
And the same is true for a delete request.
If you want to test the application, open a new terminal and run the following.
Testing the application
Once all components are up and running, we can open the http://localhost:3000 URL, and you should see the sample blog. From there, you can create new blog posts, read an existing entry, add a comment, or delete that entry.