I am trying to make na MVC Express.js application skeleton, and I want to separate controllers from models. I can easily do this in the controller, or in model. But I would like to keep DB logic in models, and actually work on the data returned by the model in my controllers.
I have this piece of code (My Controller):
user.findById(78, function (err, result) {
console.log(result);
});
and the actualy findByID implementation (My Model):
Start.prototype.findById = function(id, callback) {
var queryString = 'SELECT * FROM users WHERE userId=' + "'" + id + "'";
request.query(queryString, function (error, result) {
if (error) {
return;
}
callback (result);
});
This is query toward the MsSQL server, and it either returns an error or result.
My question is how can I in the first code example actually receive back an error or the result. Right now there is no connection. Result is properly fetched in the second code, but it never gets returned to the caller function.
After some trying I come up with this idea, that apparently works. Is this the normal way of doing it, or do I need to change something?
Start.prototype.findById = function(id, callback) {
var queryString = 'SELECT * FROM users WHERE userId=' + "'" + id + "'";
request.query(queryString, function (error, result) {
if (error) {
callback (error);
}
callback (result);
});
function doSomething(callback, id) {
user.findById(id, callback);
callback(result);
}
function foo(result) {
console.log(result);
}
doSomething(foo, 78);