I often encounter problems in terms of design if it comes to this point:
var pages,
book
;
Book.findOne( { title: "First Book" }, function(err, doc) {
pages = doc.pages;
console.log( pages );
} );
res.json(pages, 200);
pages is undefined, though I set it to doc.pages. If I move the res.json(pages, 200) into the callback of findOne this script works perfectly.
Am I following a wrong pattern/code design when it comes to JavaScript or is there a solution to keep the res.json() out of the callback, apart from making pages global?
The problem is that you’re passing
Book.findOnea callback to be executed when a match is found. Afterwards you’re invokingres.json, and passing itpagesas an argument. It’s important to understand that the callback will not have been executed by this time. Are you able to move the response inside the callback function?