I wanted to make sure that my mongodb connected successfully in the function mongoConnect, before I start quering on it, because in NodeJS is non blocking and it keeps on going executing statements
I just wanted to know if there is some function like ".then(function(){..})" on the server side or anyother thing like that, i know there are callback functions which are used for the purpose but i dont know how to use it here, i mean in my case.
Heres my code:
io.sockets.on('connection', function (socket) {
mongoConnect();
//Some Query to the Database
socket.on('login',function(user)
{
controller.loginUser(user);
});
});
function mongoConnect()
{
var mongoose = require('mongoose');
mongoose.connect('mongodb://xxxxxx-xxx-xxx.mongolab.com:xxx/xxxx');
}
You can use mongoose.once to wait for the 'open' event and then, execute your callback.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function callback () {
// Stuff here
});
Check this site for reference: http://mongoosejs.com/docs/index.html