title: Synchronous function calls for nodejs mongodb driver
body: <p>I have an open source project that deals with mongodb database. I am trying to make a function that queries the database to check if entry exists. </p>
  
  <p>The problem is when <code>if_exists()</code> returning true or false it returns undefined since the mongodb driver function is asynchronous. The file is <a href="https://github.com/WeaponXI/cplog/blob/a12338540cf784080e907f0f5b04e12187819464/routes/tagxi/query.js" rel="nofollow noreferrer">Query.js</a> and I have tried the solution here to workaround the problem <a href="https://stackoverflow.com/questions/12030248/what-is-the-right-way-to-make-a-synchronous-mongodb-query-in-node-js">What is the right way to make a synchronous MongoDB query in Node.js?</a> but still I get an undefined result with the get method.</p>
  
  <p>What is the best way to make this work?</p>
  
  <p>The output from the unit tests is as the following:</p>
  
  <pre><code>running unit tests...
  add query test
  exists tests:
  get: undefined
  {}
  should be true: undefined
  get: undefined
  {}
  should be false:undefined
  Captains Logs listening on port 3000
  Captains_Logs v0.5.0-21
  [ { name: 'rhcp', _id: 50cbdcbe9c3cf97203000002 } ]
  [ { name: 'os', _id: 50cbdcbe9c3cf97203000001 } ]
  </code></pre>
  
  <p>You can browse the whole codes at <a href="https://github.com/WeaponXI/cplog" rel="nofollow noreferrer">WeaponXI/cplog</a></p>
  
  <p>Or for a quick look the query.js code is:</p>
  
  <pre><code>var DB = require('../../lib/db.js').DB;
  
  function methods() {
    //query object
    var Q = {};
    //will act as our private variables to workaround asynchronous functions.
    //will delete non-required ones when done -- we don't have to, but just for continuity.
    exports.privates = {};
  
  
  
  
    //add tag to collection
    Q.add = function(tag) {
      if (typeof tag === "string") {
        //maybe we are adding a tag by name
        var obj = {
          name: tag
        };
      } else if (typeof tag === "object" &amp;&amp; tag.name) {
        //maybe the tag object was specified, and tag's name was provided
        var obj = tag;
      }
  
      require('mongodb').connect(DB.mongo_url, function(err, db) {
        db.collection('tags', function(err, coll) {
          coll.insert(obj, {
            safe: true
          }, function(err, result) {
            console.log(result);
  
          });
  
        });
      });
    }
    var callback = {
      _set: function(key, val) {
        exports.privates[key] = val;
        //console.log(JSON.stringify(privates));
      },
      _get: function(key) {
        console.log("get: "+exports.privates.key);
        console.log(JSON.stringify(exports.privates));
        return exports.privates[key];
      },
      _unset: function(key) {
        delete privates[key];
      }
    }
    var if_exists = function(query, where, callback) {
  
      require('mongodb').connect(DB.mongo_url, function(err, db) {
        db.collection(where, function(err, coll) {
          coll.findOne(query, function(e, r) {
            //console.log(r);
            if (r === null) {
              callback._set("does_exist", false);
            } else {
              callback._set("does_exist", true);
            }
  
          });
        });
      });
  
      var result = callback._get("does_exist");
      // delete privates.does_exist;
  
      return result;
    }
  
    Q.if_exists = function(query, where) {
      if_exists(query, where, callback);
  
    }
  
  
  
    return Q;
  }
  
  var query = exports.query = methods();
  
  function unit_test_add() {
    console.log("add query test");
    query.add("os");
    query.add({
      name: "rhcp"
    });
  }
  
  function unit_test_if_exists() {
    console.log("exists tests:");
    console.log("should be true: " + query.if_exists({
      name: "os"
    }, "tags"));
    console.log("should be false:" + query.if_exists({
      name: "ossuruk"
    }, "tags"));
  
  }
  
  function unit_tests() {
    console.log("running unit tests...");
    unit_test_add();
    unit_test_if_exists();
  
  }
  unit_tests();
  </code></pre>
  
  <h3>Solution:</h3>
  
  <p><a href="https://gist.github.com/4291691" rel="nofollow noreferrer">Query.js Query.test.js Gists</a></p>
  
  <p>Thanks JohnnyHK!</p>