I am working on a nodejs app.
Folder structure is
app
app.js
package.json
../model/schema.js
../controller/controller.js
../views
All the logic is in controller.js while app.js performing routing itself....
I want to know how to get/return data(object) from controller.js to app.js.
I am using 'return' to send mongodb document from controller to app but its undefined.
Heres code of app.js..i have removed unneccessary code
var express = require('express'),
app = express.createServer(express.logger()),
io = require('socket.io').listen(app),
routes = require('./routes');
var controller=require('./controller/controller');
var model=require('./model/schema');
app.get("/", function(req, res) {
res.render("chatroom.html");
});
io.sockets.on('connection', function (socket) {
socket.on('login',function(user)
{
var onliner=controller.loginUser(user);
console.log("Onlinersss: ",onliner);
});
socket.on('registerUser',function(user){
controller.registerUser(user);
});
});
Heres controller.js code:
var model=require('../model/schema');
exports.loginUser=function(user)
{
model.registerUser.findOne({uname:user.uname,pass:user.pass},function(err,doc){
if(!err){
console.log("Here loggedin: ",doc);
return doc;
}
else
console.log("Invalid username or password");
});
};
JavaScript (and therefore node.js) is asynchronous. When you 'return doc' the anonymous function defined at function(err, doc) is returned... not the function loginUser that you are trying to get data from.
loginUser returns immediately, and it returns undefined (since you don't specify anything else). To see what I mean, put 'return true;' as the last line in loginUser and you'll notice that you get the value back of 'true.'
However, you don't want to return a value. You want to callback with a value. That's beyond the scope of a stackoverflow answer, so here is a good resource:
http://bjouhier.wordpress.com/2011/01/09/asynchronous-javascript-the-tale-of-harry/
I've just pushed a project to GitHub that uses pretty much the same libraries and RethinkDB as the database (very similar to MongoDB). Basically you need to pass callbacks to your controller and have them invoked with the data retrieved from the DB. Take a look at app.js and lib/db.js in the linked project.