Add CRUD Features for Blog Data
Learn how to add CRUD features in the GraphQL application with MongoDB.
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. ...