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.
// GetAllBlogs returns all blogs from the databasefunc (b *BlogService) GetAllBlogs() []*model.Blog {// create a query to get all blog datavar query primitive.D = bson.D{{}}// create a find option to order blog data by createdAtvar findOptions *options.FindOptions = options.Find()// set sort to sort the blog data by createdAt// the recently created blog will be displayed firstfindOptions.SetSort(bson.D{{Key: "createdAt", Value: -1}})// get all blog data from the databasecursor, err := database.GetCollection(BLOG_COLLECTION).Find(context.TODO(), query, findOptions)// if the operation failed, return an empty sliceif err != nil {return []*model.Blog{}}// create a variable to store all blog datavar blogs []*model.Blog = make([]*model.Blog, 0)// iterate through all the blog data// each blog data is inserted into the "blogs" variableif err := cursor.All(context.TODO(), &blogs); err != nil {return []*model.Blog{}}// return all blog data from the databasereturn blogs}
Below is an explanation of the code above:
-
In line 4, the
query
variable contains a query to get all blog data. -
In line 7, the
findOptions
variable contains an additional option to sort the blog data bycreatedAt
so 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 thecursor
variable. -
In line 26, the
All()
function that’s called from thecursor
returns all blog data that’s ...