Hey! I need some help understanding what’s going on here…
I have been taking this Mongo DB course and the final project is making this website. My confusion is how this callback situation is working. For the first task, I am supposed to make a function that query’s all the categories from the items in a database (for a store) and make an array of the item categories and the totals. I have figured out who to actually create the function using some help online, but I really don’t understand what’s happening with the final callback(result). I’m lost as to how that relates to the initial this.getCategories = function (callback).
Here are some parts of the app that might be helpful. I feel like I have usually understood callbacks, but feel jumping into the “deep end” with this node/express app (I’m pretty new to that) is revealing things about callbacks that I don’t totally understand…
*Side note: most of this app was pre-written for the assignment, and I am just trying to fill in gaps, hence things like the entire MongoClient below that’s completed for me already.
This is part of me items.js file that has the function in question I’m not really understanding.
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
function ItemDAO(database) {
"use strict";
this.db = database;
this.getCategories = function (callback) {
"use strict";
var categoryArray = this.db.collection("item").aggregate([{
$match: {
"category": {
$exists: true
}
}
},
{
$group: {
_id: "$category",
num: {
$sum: 1
}
}
},
{
$sort: {
"_id.category": 1
}
}
]).toArray(function makeArray(err, result) {
var allItems = 0;
for (var i = 0; i < result.length; i++) {
allItems += result[i].num;
};
result.unshift({
_id: "All",
num: allItems
})
console.log(result);
callback(result);
});
}
This is the mongomart.js file (the part that establoishes the connection) that has the homepage where the function is getting used, in case that helps at all.
MongoClient.connect('mongodb://localhost:27017/mongomart', function (err, db) {
"use strict";
assert.equal(null, err);
console.log("Successfully connected to MongoDB.");
var items = new ItemDAO(db);
var cart = new CartDAO(db);
var router = express.Router();
// Homepage
router.get("/", function (req, res) {
"use strict";
var page = req.query.page ? parseInt(req.query.page) : 0;
var category = req.query.category ? req.query.category : "All";
items.getCategories(function (categories) {
items.getItems(category, page, ITEMS_PER_PAGE, function (pageItems) {
items.getNumItems(category, function (itemCount) {
var numPages = 0;
if (itemCount > ITEMS_PER_PAGE) {
numPages = Math.ceil(itemCount / ITEMS_PER_PAGE);
}
res.render('home', {
category_param: category,
categories: categories,
useRangeBasedPagination: false,
itemCount: itemCount,
pages: numPages,
page: page,
items: pageItems
});
});
});
});
});