Creating an Admin Dashboard

Learn how to use the MongoDB aggregate function to group data.

Let’s create a page where we can view book sales and perform some aggregate functions using MongoDB.

Publishing sales data

Open the imports/api/bookSales/server/publication.js file. On line 2, the BookSales collection is imported for use. A publication is defined on lines 4–6, which we named bookSales.sales. This publication returns a cursor from the BookSales collection of documents in which the paymentStatus field is equal to success.

Subscribing to the sales cursor

After creating a publication, we’ll want to subscribe to the cursor on the client. Open the imports/ui/Sales.jsx file. On line 3, we import the useTracker function. On line 4, we import the BookSales collection. Inside the useTracker function, we subscribe to the publication named bookSales.sales.

The function returns an object with the loading and sales keys. The value of loading is the state of the subscription handle, while sales retrieves all book sales that match the criteria of the publication.

The sales variable is an array that we’ll loop over to render an HTML table that displays the sales. On line 20, we define a total variable that will be used to sum the number of books bought. On line 45, the totalSum destructured from the sales is added to the total to get a grand total of all books bought.

Task

Click the “Run” button to start the application. Buy some books, and, after buying the books, log in as an administrator to view the Sales component present in the AdminDashboard component.

Get hands-on with 1400+ tech skills courses.