Nodejs and MongoDB Modules

Need help with an engine or coding not on the list? Need help with a game or the website and forums here? Direct all questions here.
Post Reply
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Nodejs and MongoDB Modules

Post by hallsofvallhalla »

Okay so I have been racking my brain on this and I know I missing something simple. I am not using Mongoose or anything else other than mongojs.

All I want to do is hold my DB code outside of the app.js folder so i am using export

so in app.js

Code: Select all

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , PlayerDB = require('./functions/server/PlayerDB')

 var databaseUrl = "chatarena"; 
var collections = ["Players"]
var db = require("mongojs").connect(databaseUrl, collections);
var Player = new PlayerDB();
console.log(Player.checkUser(db,"Halls"));



and in PlayerDB.js

Code: Select all

var PlayerDB = function (){  
   var self = this;
   self.checkUser = function (db,Name)
   {
		db.Players.find({Name: Name}, function(err, Players) 
		{
		  if( err || !Players) return "No Players by that name";
		  else Players.forEach( function(Player) {
			return Player.Strength;
		  } );
		});
   };
   
};

module.exports = PlayerDB;
Basically this will not work as returning a function gives the entire object. It is a function inside of a function so scope will not allow me to set a variable to pass back. What the heck am i doing wrong here? How is it done normally to use MongoDB inside of Nodejs and yet hold the code outside of the app.js?
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Re: Nodejs and MongoDB Modules

Post by hallsofvallhalla »

OMG ^&(&*%$ I finally figured it out. That was hours of racking my brain for such a simple solution. It was all in call backs

Code: Select all

Player.checkUser(db,"Halls", function(result) {
  console.log(result);
});

Code: Select all

 self.checkUser = function (db,Name,callback)
   {
		db.Players.find({Name: Name}, function(err, Players) 
		{
		  if( err || !Players) console.log(0);
		  else Players.forEach( function(Player) {
			var Test = Player.Strength;
			callback(Test);
		  } );
		});
		
   };

};
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Nodejs and MongoDB Modules

Post by Jackolantern »

Yep, that is that "volleying" pattern I mentioned in that other thread. It is really a huge piece of dealing with async code, but once you get the hand of it, a lot of stuff falls into place :cool:
The indelible lord of tl;dr
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Re: Nodejs and MongoDB Modules

Post by hallsofvallhalla »

yeah it is definitely one of those things that has to "click".
Post Reply

Return to “Advanced Help and Support”