...

/

Add CRUD Features for Blog Data

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 database
func (b *BlogService) GetAllBlogs() []*model.Blog {
// create a query to get all blog data
var query primitive.D = bson.D{{}}
// create a find option to order blog data by createdAt
var findOptions *options.FindOptions = options.Find()
// set sort to sort the blog data by createdAt
// the recently created blog will be displayed first
findOptions.SetSort(bson.D{{Key: "createdAt", Value: -1}})
// get all blog data from the database
cursor, err := database.GetCollection(BLOG_COLLECTION).Find(context.TODO(), query, findOptions)
// if the operation failed, return an empty slice
if err != nil {
return []*model.Blog{}
}
// create a variable to store all blog data
var blogs []*model.Blog = make([]*model.Blog, 0)
// iterate through all the blog data
// each blog data is inserted into the "blogs" variable
if err := cursor.All(context.TODO(), &blogs); err != nil {
return []*model.Blog{}
}
// return all blog data from the database
return blogs
}
Get all 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 by createdAt 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 the cursor variable.

  • In line 26, the All() function that’s called from the cursor returns all blog data that’s ...