MongoDB trouble for URL Shortener API

Hello,

I am currently working on the URL shortener API and am having some trouble getting my mongodb functions to work properly. I am creating the project on glitch and have created a mongodb module to handle all the database functions. One of the functions is to check whether the new URL input already exists in the database. Assume I have all the necessary import statements:

var checkIsNew = function(url){
  console.log("entering check");
  mongo.connect(MONGODB_URI, function(err, db){
    if(err) throw err;
    var collection = db.collection("collectionName");
    collection.find({originalurl : url}).toArray(function(err, docs){
      if(err) throw err;
      console.log("exiting check");
      if(docs.length > 0){
        return false;
      } else {
        return true;
      }
    });
  });
}

The function is supposed to return false if no docs containing the url exists or true if otherwise. You can see that I’ve added two console.logs to test this out. When I import this function to my entry point and run a console.log(checkIsNew(someURL)), I get:

entering check
undefined
exiting check

This seems to indicate that the function is returning an undefined rather a real boolean before the entire function script is even run. So my questions are:

  1. Are mongo connections asynchronous? Is that why my result is what it is?
  2. If so, how do I deal? Do I wrap the function in a promise? Does Mongoose solve this problem?

Thanks,

  1. Yeah you’re getting ‘undefined’ before ‘exiting check’ so that seems to be the problem.
  2. This gave me trouble too. What worked for me was to put all the tasks (checking for existing input, create new short URL, etc.) inside of the app.get() call.
mongo.connect(MONGODB_URI, function(err, db){     
    var collection = db.collection("collectionName");
    app.get("/*", function(req, res) {
        //do all your stuff here like coll.find...
    });
    app.listen....
}

Thanks, that worked :slight_smile: Wish there was a way to be more modular with these mongo functions though. I guess for more complex dbs, it may be possible.

You’re welcome! I think codes with mongoose looks cleaner and easy to follow… I’m still learning how to use it though :stuck_out_tongue: