I am new to node.js so please bear with me.
I am wondering what is the proper way to pass the model to the controller in node. I sort of having it working but when I call a method from the model in my controller what I have returning from the model is 'undefined' and I am not sure why. My connection to the DB is fine. Take a look at my files and see my comments in all caps.
routes.js
module.exports = function(app, dbConnection) {
var theIndexModel = require('../models/index.server.models')(dbConnection);
var index = require('../controllers/index.server.controller')(theIndexModel);
app.get('/', index.homePage);
};
models.js
function IndexModel(dbConnection) {
modelMethods = {};
modelMethods.getAllUsers = function(req, res) {
var query = "SELECT * FROM `users`";
dbConnection.query(query, function(err, rows, fields) {
return rows; //NOT RETURNING ANYTHING WHEN I CALL FROM CONTOLLER!!
});
};
return modelMethods;
}
module.exports = IndexModel;
controller.js
function IndexController(theIndexModel) {
controllerMethods = {};
controllerMethods.homePage = function(req, res) {
console.log(theIndexModel.getAllUsers()); //UNDEFINED HERE, WHEN I SHOULD BE GETTING USERS FROM THE DB
res.render('index', {
title: 'hello'
});
};
// Return the object that holds the methods.
return controllerMethods;
}
module.exports = IndexController;
What am I doing wrong? Thanks in advance.
As pointed by NG, your problem is with asyc code. return rows is returning the rows, only you are never catching it.
To fix this, you can learn about promises, or dive into callback hell.
If you choose the callback hell, it will look something like this:
controller.js
function IndexController(theIndexModel) {
controllerMethods = {};
controllerMethods.homePage = function(req, res) {
theIndexModel.getAllUsers(function(err, rows, fields){
res.render('index', {
title: 'hello,
users: rows
});
});
};
// Return the object that holds the methods.
return controllerMethods;
}
module.exports = IndexController;
and models.js
function IndexModel(dbConnection) {
modelMethods = {};
modelMethods.getAllUsers = function(cb) {
var query = "SELECT * FROM `users`";
dbConnection.query(query, cb);
};
return modelMethods;
}
module.exports = IndexModel;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With