Add CRUD Features for Blog Data
Explore how to implement CRUD operations for blog data in a Go backend application using GraphQL and MongoDB. Learn techniques to query all blogs, get blogs by ID, create new entries, update existing blogs, and delete blogs from persistent storage, enhancing your understanding of backend development with Go.
Use the database queries in the service component
We replace the local storage with persistent storage using the MongoDB database.
Inside the service.go in the service directory, we create a constant to store the collection name for blog data.
const BLOG_COLLECTION = "blogs"
Get all blogs
We modify the GetAllBlogs() function to get all blog data from the database.
Below is an explanation of the code above:
-
In line 4, the
queryvariable contains a query to get all blog data. -
In line 7, the
findOptionsvariable contains an additional option to sort the blog data bycreatedAtso the recently created blog will be displayed first. -
In line 14, the
Find()function returns all blog data in a cursor format. All blog data is stored inside thecursorvariable. -
In line 26, the
All()function that’s called from thecursorreturns all blog data that’s inserted into theblogsvariable. ...