title: Callback at MongoDB Operation With Node.js
body: <p>For organization purposes I'm separating my source code into modules, for example I have the <code>user</code> module on my node.js app which is responsable for retrieving user information from a MongoDB database. I'm doing something like this:</p>
  
  <pre><code>var mongo = require("mongodb"),
      Server = mongo.Server,
      Db = mongo.Db;
  
  var server = new Server("localhost", 27017, { auto_reconnect: true });
  var db = new Db("users", server);
  
  module.exports = {
      login: function(user, pass, callback) {
          var reg_result = null;
  
          db.open(function (err, db) {
              if(!err) {
                  db.collection("users", function(err, collection) {
                      collection.findOne(
                          {
                              "username": user,
                              "password": pass
                          },
                          function(err, item) {
                              if(!err) {
                                  reg_result = item;
                              } else {
                                  reg_result = "error";
                              }
                          }
                      );
                  });
              } else {
                  reg_result = "error";
                  console.log("ERROR: " + err);
              }
          });
  
          callback(reg_result);
      }
  }
  </code></pre>
  
  <p>And executing it on my test script like this:</p>
  
  <pre><code>var user = require("./user.js");
  
  user.log("test", "test", function(msg) {
      console.log(msg);
  });
  </code></pre>
  
  <p>It does the database operation and retrieves the value, but every time it only returns <code>null</code>, when I don't initialize the <code>reg_result</code> variable it returns <code>undefined</code>. What should I do to correct this?</p>
  
  <p><em>I debugged using <code>console.log</code> on the <code>user.js</code> and the <code>item</code> was outputted, but I want to have the callback so I can use the item on other sources, like my test script</em></p>