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:
- Are mongo connections asynchronous? Is that why my result is what it is?
- If so, how do I deal? Do I wrap the function in a promise? Does Mongoose solve this problem?
Thanks,