Can't deploy app with MongoDB to Heroku. <SOLVED>

Hi! First of all, thank you so much for your help, I really appreciate it.

I’m working on my URL-shortener and everything works perfectly when I work with my local database, and with my mLab database on cloud9, but when I deploy my project to heroku, it gives me an error (503) and says that my application could not be served. It’s my first time deploying to Heroku using mongoDB

So… I decided to test if my app or my deployment process to heroku were causing the problem. I made a small sample program that inserts documents into my mLab database that works great on cloud9 to try deploying to heroku a simple program, but on heroku it doesn’t work, this is the message I get:

Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details

But when I check on the logs and build log, there is no error, it says built finished.

The console says

Failed to load resource: the server responded with a status of 503 (Service Unavailable)

Here is my server.js code:

var express = require('express');
var mongo = require("mongodb").MongoClient;

var dataURL = process.env.MONGOLAB_URI;

var app = express();

app.get('/', function (req, res) {
    
    res.writeHead(200, {'content-type':'application/JSON'});
    
    mongo.connect(dataURL, function(err, db) {
       if (err) throw err;
       
       var collection = db.collection('data');
       
       collection.insert({
           "key" :"test"
       }, function(err, data) {
          if (err) throw err;
          
          db.close();
          res.end(JSON.stringify(data["ops"][0]));
       });
    });
    
})

app.listen(process.env.PORT, function () {
  console.log('Example app listening on port!');
})

I declared an environment variable for my mLab URI and it works great on cloud9, on Heroku I added it using the settings tab as well.

And the port is defined by the environment, not fixed.

I seriously appreciate your help! Thank you! :smile:

IT WORKED!!! :grin:

If any camper is having this problem, I got it to work by making these changes:

  • Saved mongodb as a dependency, when I install it with npm install mongodb –save , include --save.
  • In package.json I changed “main” value to “server.js”

Good luck! :smile: