Monday 5 June 2017

Using function inside MongoDB query and variable scope

I want to code a little app where I can store the incoming request url, named reqUrl below, and check if it already exists by using the compareUrls function.

It returns true if both websites are in the same domain and false otherwise, for example when doing compareUrls(stackoverflow.com, http://www.stackoverflow.com). This is used so as not to add duplicate urls.

I am trying to use that function inside a MongoDB query like this:

db.collection("mydb").find({$where: function() {

         if (compareUrls(reqUrl, this.url) //if true, simply return the url
         {
            return this.url;
         } else { //if not existing insert it into the database
            db.collection("mydb").insert({"url":reqUrl});
         };          
}}).toArray();

Now the problem is that because of scoping, the reqUrl variable is not recognized, and I don't know any workaround. I thought about retrieving back all results to an array by simply calling .find and checking reqUrl against each item, but that would be far more than efficient.

Please note that I am very new to MongoDB.

Any feedback would be appreciated, thanks.



via Valilutzik

No comments:

Post a Comment