Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a REST API With Express Modeling Data for the API Getting More from Mongoose

Jesse Thompson
Jesse Thompson
10,684 Points

Im trying to understand how 'callback' works.

My understanding of the below code is that at req.answer.vote(req.vote, function.... is that it runs the vote method in the model.js file ON the answer in the request. It passes the callback in the routes.js file to the AnswerSchema.method as an argument. Then at the end once it does what it has to do in the mongodb it saves then runs the rest of the callback in routes.js being function(err, question) { console.log(req.vote); if(err) return next(err); res.json(question); });

Is that correct? The callback parameter has been a little convoluted to me.

// routes.js file
router.post("/:qId/answers/:aId/vote-:dir", function(req, res, next) {
        if(req.params.dir.search(/^(up|down)$/) === -1) {
            const err = new Error("Not Found");
            err.status = 404;
            next(err);
        } else {
            req.vote = req.params.dir;
            next();
        }
    }, function(req, res, next) {
        req.answer.vote(req.vote, function(err, question) {
            console.log(req.vote);
            if(err) return next(err);
            res.json(question);
    });
});
// models.js file
AnswerSchema.method("vote", function(vote, callback) {
    if(vote === "up") {
        this.votes += 1;
    } else {
        this.votes -= 1;
    }
    this.parent().save(callback);
});