The enrollment stats API

In order to implement a backend API that will query the Enrollments collection in the database to calculate the stats for a specific course, we first need to declare a GET route at '/api/enrollment/stats/:courseId', as shown in the following code.

mern-classroom/server/routes/enrollment.routes.js

router.route('/api/enrollment/stats/:courseId')
.get(enrollmentCtrl.enrollmentStats)

A GET request at this URL will return a stats object containing the total enrollments and total completions for the course, as identified by the courseId provided in the URL parameter. This implementation is defined in the enrollmentStats controller method, as shown in the following code.

mern-classroom/server/controllers/enrollment.controller.js

const enrollmentStats = async (req, res) => {
try {
let stats = {}
stats.totalEnrolled = await Enrollment.find({course:req.course._id})
.countDocuments()
stats.totalCompleted = await Enrollment.find({course:req.course._id})
.exists('completed', true)
.countDocuments()
res.json(stats)
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}

In this enrollmentStats method, we run two queries against the Enrollments collection using the course ID that is provided in the request. In the first query, we simply find all the enrollments for the given course, and count these results using MongoDB's countDocuments(). In the second query, we find all the enrollments for the given course, and also check whether the completed field exists in these enrollments. Then we finally get the count of these results. These numbers are sent back in the response to the client.

Similar to other API implementations, you will also need to define a corresponding fetch method on the client that will make the GET request to this route. Using this fetch method, we will retrieve and display these stats for each published course, as discussed in the next section. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset