0

Currently, I have this config section to run with Heroku's mlab, or locally if it's in development

 var env = process.env.NODE_ENV || 'development';

 if (env === 'development') {
     process.env.PORT = 3000;
     process.env.MONGODB_URI = 'mongodb://localhost:27017/manage';
 } else if (env === 'test') {
     process.env.PORT = 3000;
     process.env.MONGODB_URI = 'mongodb://localhost:27017/manage-test';
 }

which is working for the authentication section of my code. However, I have to access another collection within that database, and currently, I'm connecting it locally with

app.get('/auth-home', isLoggedIn, (req, res) => {
    MongoClient.connect("mongodb://localhost:27017/manage", (err, db) => {
        db.collection("home", (err, collection) => {
            collection.find().toArray((err, result) => {
                if (err) {
                    return err;
                }
            });
        });
    });
});

However, this won't connect with mlab since it's localhost. So my issue right now is that I'm not sure how to pass that config section of code into my routes as well as connecting to a different collection, and then having it work with Heroku as well.

Community
  • 1
  • 1
Justin Li
  • 91
  • 4
  • 11

1 Answers1

0

There are a few problems with how your app is configured.

One key problem is that your app isn't properly utilizing a connection pool as it is creating a new connection each time the endpoint is called. You should check out this blog post to get a better sense of how to configure the connection logic in your app.

In regards to your main question, the way you're utilizing process.env seems a little backwards. Typically process.env is used to read information stored in an environment variable. For an mLab add-on, you can read the MONGODB_URI variable to obtain the connection string for your database.

You could then use a combination of variable to tell the app to use the localhost connection string when running locally, versus the mLab URI when being run in Heroku. Something like:

// assuming 'development' is local, 'test' is heroku
var app_env = process.env.NODE_ENV || 'development';

if (app_env === 'development') {
     var app_port = 3000;
     var uri = 'mongodb://localhost:27017/manage';
} else if (app_env === 'test') {
     var app_port = 3000;
     var uri = process.env.MONGODB_URI 
}
Adam Harrison
  • 3,323
  • 2
  • 17
  • 25