如何在Handlebars模板文件中获取MongoDB聚合查询结果?
Got it, let's walk through how to display your MongoDB aggregation results in that Handlebars template. Here's what you need to do step by step:
Right now your aggregation code just logs the result—you need to fetch both the aggregation stats AND your ideas data, then pass both to your Handlebars template. Here's how to adjust your backend code:
// First, run the aggregation query to get stats Idea.aggregate([ { $group: { _id: null, totalPrice: { $sum: "$itemPrice" }, total: { $sum: 1 } } } ]) .then(aggResults => { // Grab the stats object (aggResults returns an array with one entry) const stats = aggResults[0] || { totalPrice: 0, total: 0 }; // Fetch all your ideas data return Idea.find({}).then(ideas => { // Pass both datasets to the Handlebars template res.render('your-template-filename', { ideas, stats }); }); }) .catch(err => { console.error(err); res.status(500).send('Failed to load data'); });
I used promises here for cleaner flow, but you can nest the Idea.find() call inside the aggregate callback if you prefer callback-style code. The core idea is getting both the aggregation stats and your ideas into the template's context.
Now update your template to show the total count and total price alongside your ideas list. Here's the adjusted template:
<!-- Add aggregation stats display at the top --> <div class="mb-4 p-3 bg-light rounded"> <h5>Total Ideas Listed: {{stats.total}}</h5> <h5>Total Price of All Items: ${{stats.totalPrice}}</h5> </div> <!-- Your existing ideas list code --> {{#each ideas}} <div class="card card-body mb-2"> <h4>{{title}}</h4> <p>{{details}}</p> <a class="btn btn-dark btn-block mb-2" href="/ideas/edit/{{id}}">Edit</a> <form method="post" action="/ideas/{{id}}?_method=DELETE"> <input type="hidden" name="_method" value="DELETE"> <input type="submit" class="btn btn-danger btn-block" value="Delete"> </form> </div> {{else}} <p>No video ideas listed</p> {{/each}}
Quick Notes:
- We access the aggregation data using
{{stats.total}}and{{stats.totalPrice}}—these map directly to the object we passed from the backend. - The styled div for stats is just a simple way to make the numbers stand out; you can tweak the CSS classes to match your app's design.
- The fallback
{ totalPrice: 0, total: 0 }ensures even if there are no ideas, the stats won't show up as empty or undefined.
That's all! Now when you load the page, you'll see your aggregation results displayed right above (or wherever you place them) your list of ideas.
内容的提问来源于stack exchange,提问作者Muhammad Zubair

