I was trying to use two Express param functions in one route, and one of the param functions needed the other param to be loaded. For example, if I have the route file:
// route file
app.route('/api/v1/toolboxes/:toolboxId/tools/:toolId')
...
app.param('toolboxId', controller.loadToolbox);
...
app.param('toolId', controller.loadToolAndEnsureFromToolbox);
And an associated controller:
exports.loadToolbox = function(req, res, next, id) {
// load toolbox from Mongoose into req.toolbox
req.toolbox.maker = req.toolbox.maker || 'Stanley';
};
// controller
exports.loadToolAndEnsureFromToolbox = function(req, res, next, id) {
Tool.findAsync({
_id: id,
}).then(function(tool) {
if (!tool) {
res.status(404).send("Tool not found");
} else if (tool.maker !== req.toolbox.maker) { // <<<<<
res.status(403).send("This tool isn't from the right maker!");
} else {
req.tool = tool;
...
next();
}
});
...
};
I wasn’t positive that toolbox would always be loaded when I wanted to check it in tool. (This is kind of a strange example, but it resembles a problem that I was trying to solve.)