2

I've been experimenting with the API of flickr and am looking to deploy the application to Heroku now that I am finished. In order to do this, since I'm using MongoDB, I'm trying to get it to run with mLab. I can log into the shell just fine, I can get the entire thing to run when I use the URL to the database as a string, but suddenly when I assign that URL to process.env.MONGOLAB_URI with SET MONGOLAB_URI="mongodb://dbuser:dbpassword@ds041506.mlab.com:41506/flick r_image_search" (I'm using Windows 10) in the local command line and try to use it, it stops working. The error message I'm getting is "Error: invalid schema, expected mongodb". Even when I used console.log(url) it returned "mongodb://dbuser:dbpassword@ds041506.mlab.com:41506/flickr_image_search" (I guarantee the username and password I used in the command line are both absolutely correct considering I literally copy+pasted the URL I used that worked into the command line) as I would expect. The IDE I'm using is Visual Studio Code and I haven't been using the heroku mLab add-on to run this but my database on the website itself. I'm out of ideas and can use some help. Here's each relevant file of code I'm using for the application:

app.js

var express = require('express');
var app = express();
var flickr = require('./flickr.js');
var mongo = require('mongodb').MongoClient;
var path = require('path');
var url = process.env.MONGOLAB_URI;

var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var mins = today.getMinutes();
var hr = today.getHours();

today = month + '/' + day + '/' + year + ' ' + hr + ':' + mins;

var obj;
var search;

app.get('/', function(req, res){
  res.sendFile(path.join(__dirname + '/index.html'));
});

app.get('/latest', function(req, res){
    mongo.connect(url, function(err, db){
        if(err) throw err;
        var theCollection = db.collection('flickr_image_search');
        theCollection.find({}).toArray(function(err, docs){
            if(err) throw err;
            search = docs;
            return docs;
        });
        db.close();
    });
    res.send(search);
});

app.get(['/search/:text/:offSet2', '/search/:text'], function(req, res){
    var lookInIt = req.params.text;
    var listLength = req.params.offSet2;
    var searched = flickr.search(lookInIt, listLength || 10);

    obj = {
            query: lookInIt,
            offSet: listLength,
            date: today
        };

    mongo.connect(url, function(err, db){
        if(err) throw err;
        var imageSearch = db.collection('flickr_image_search');
        imageSearch.insert(obj);
        db.close();
    });

    res.send(searched);

});


var port = 3000 || process.env.PORT;

app.listen(port, process.env.IP, function(){
    console.log('LISTENING');
});

flickr.js

var private = require('./private');    

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: private.key,
      secret: private.secret
    };

var obj;

function search (query, offSet) {
    Flickr.tokenOnly(flickrOptions, function (err, flickr) {
        if (err) throw err; 
        flickr.photos.search({
            text: query,
            page: 1,
            per_page: offSet,
            sort: "relevance"
        }, function (err, result){
            if(err) throw err;

            result = result.photos.photo;

            for(var key in result){ 

                var picUrl = 'https://farm' + result[key]["farm"] + '.staticflickr.com/' + result[key]["server"] + '/' + result[key].id + '_' + result[key].secret + '.jpg'
                result[key].picUrl = picUrl;

                var userUrl = 'https://www.flickr.com/photos/' + result[key].owner + '/' + result[key].id;
                result[key].userUrl = userUrl;

                delete result[key]["ispublic"];
                delete result[key]["isfriend"];
                delete result[key]['isfamily'];
                delete result[key]['id'];
                delete result[key]['owner'];
                delete result[key]['server'];
                delete result[key]['farm'];
                delete result[key]['secret'];
            }
            obj = result;   
        }); 

    });

    return obj;
}

module.exports.search = search;

index.html

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<title>flickr Image Search</title>

<div class='container'>
  <h1 class='text-center'>Flickr Image Search</h1>

  <h3 class='well'>To get a series of URLs for images, type 'search/whatever-you-want-to-search/the-amount-of-photos-you-want-returned' in the address bar after 'someWebsite.com/'.
    If you want to see the most latest searches that were searched, instead of 'search/whatever-you-want-to-search/the-amount-of-photos-you-want-returned' type 'latest'.  
    When you find the URL that you want, just copy+paste!</h3>

  <p class=lead>This application is purely functional, so chances are the queries won't return clean.</p>
  <p>This is an application that searches through the photos of Flickr, using its API.</p>
</div>
DougCal
  • 105
  • 1
  • 1
  • 11
  • When setting the environment variable, did you mean the following: `heroku config:set MONGOLAB_URI=mongodb://dbuser:dbpassword@ds041506.mlab.com:41506/flickr_image_search`, or is the command different on Windows? https://devcenter.heroku.com/articles/config-vars – pneumee Sep 26 '16 at 22:23
  • 1
    Should've specified. When I tested locally, that's when I did `SET MONGOLAB_URI="mongodb://dbuser:dbpassword@ds041506.mlab.com:41506/flickr_image_search"`. Before I even tried doing that though, I tried doing it with the string URL, which worked. After the SET command failed, that's when I went ahead and did the command `heroku config:set MONGOLAB_URI=mongodb://dbuser:dbpassword@ds041506.mlab.com:4‌​1506/flickr_image_se‌​arch`, and then deployed to Heroku to see if it would work there. Neither of those gave me any success. – DougCal Sep 26 '16 at 23:50
  • After setting the `MONGOLAB_URI` environment variable, can you successfully get it via `heroku config:get MONGOLAB_URI` ? If so, logging it to the console while running on heroku logs the correct uri? And if it's logging what you expect, are you getting the same "Error: invalid schema, expected mongodb" error upon connecting? – pneumee Sep 27 '16 at 15:25
  • 1
    I'm not sure how to check it on Heroku, especially since the app doesn't want to run on there. Heroku has been giving me troubles when deploying applications in general. The only time I ever got an application to work was my first one that I deployed, and it didn't even have a Procfile (but it did have only one js file). The second one I attempted to deploy had only one js file also, but that didn't work, even after adding a Procfile. So, to put it short, no. – DougCal Sep 29 '16 at 15:07

2 Answers2

5

Heroku uses MONGODB_URI, but you have MONGOLAB_URI.

This could explain why the string works but the environment variable doesn't.

Try typing this in your shell: heroku config

Find the heroku config variable. I would venture to guess it is MONGODB_URI and not MONGOLAB_URI.

If this is the case, reset your environment and heroku config variable to use MONGODB_URI.

You said in a comment: "I'm not sure how to check it on Heroku, especially since the app doesn't want to run on there. Heroku has been giving me troubles when deploying applications in general."

To check your config variables, you can type heroku config in your shell, or you can navigate to your apps dashboard. Click on Settings. Click on Reveal Config Vars. enter image description here

While you are in the dashboard, you can provision the mLab Add-on that Heroku provides by clicking on the Resources tab. Then in the Add-on's search box, type in mLab MongoDB. enter image description here Click on it. This will take you to mLab's GUI where you can view and manage your collections.

If you are wondering what the server setup looks like, see the code below. This will connect to both your local and mLab db where appropriate.

if(process.env.MONGODB_URI) {
 mongoose.connect(process.env.MONGODB_URI);

}else {

 mongoose.connect(db, function(err){ //db = 'mongodb://localhost/yourdb'
  if(err){
   console.log(err);
  }else {
   console.log('mongoose connection is successful on: ' + db);
  }
 });
}
govgo
  • 625
  • 6
  • 18
  • 2
    Sorry for taking this long to respond, I've been working projects. Not sure if setting the environment variable to MONGODB_URI helped or not, but what ended up being the problem was the way I was setting the code in the command line, and the port variable. I kept using `MONGODB_URI="mongodb://dbuser:dbpassword@ds041506.mlab.com:‌​41506/flickr_image_s‌​earch"` as oppose to `MONGODB_URI=mongodb://dbuser:dbpassword@ds041506.mlab.com:‌​41506/flickr_image_s‌​earch`. Lastly, setting the port to `3000 || process.env.PORT` doesn't seem to work, but when I set port to `process.env.PORT` it runs fine – DougCal Oct 05 '16 at 22:36
  • 1
    Lost room in the previous comment. The reason why I'm skeptical as to setting the environment variable to MONGODB_URI was helpful is because I would set MONGOLAB_URI in the command line with the following command: `heroku config:set MONGOLAB_URI=mongodb://dbuser:dbpassword@ds041506.mlab.com:‌‌​​41506/flickr_image_‌​s‌​earch`. After that, it will show on the activity feed on Heroku with "Set `MONGOLAB_URI` config var" as confirmation. Because of that, I think it was just how I was setting the environment variable. Thanks for helping me out! @vincentjp @pneumee – DougCal Oct 05 '16 at 22:51
2

It's been helpful to me to install dotenv (https://www.npmjs.com/package/dotenv), require('dotenv'), then dotenv.load() before declaring process.env variables. Now stuff in my .env file is read in where it wasn't before. thx.

tbushman
  • 21
  • 1
  • 2