6

Trying to connect to mongodb on MongoDB cloud from NodeJS app hosted on Heroku. Using mongodb ^3.2.3 and MongoDBClient, locally on my machine works great but after deployment to Heroku, getting the error above : "MongoError: MongoClient must be connected before calling MongoClient.prototype.db"

const uri = "mongodb+srv://myuser:mypass@mongodbcluster/test?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
    db = client.db("collection"); // <-- this is where it fails
...
RRob
  • 167
  • 1
  • 2
  • 9
  • 1
    You didn't check `err` and likely an error has occurred. More than likely since you attempt to be connecting to an Atlas cluster this is an "authentication error" since you did not supply the heroku host within the allowed whitelisted IP addresses. And you **definately** did not add to the whitelist because the heroku hosted instance has a "Dynamic IP address". Either open the allowed hosts to everything and secure authentication with certificates, or use a third party service to resolve the hostname in a way Atlas is happy with. – Neil Lunn Apr 20 '19 at 00:18
  • Not *directly* related, but the *preferred* API usage would be to call the **static** `connect()` from [`MongoClient`](http://mongodb.github.io/node-mongodb-native/3.2/api/MongoClient.html#.connect) instead i.e `MongoClient.connect(uri, options, (err, client) => { // check err, then use client })` or via Promise `MongoClient.connect(uri, options).then(client => ... ).catch(err => ...)` – Neil Lunn Apr 20 '19 at 00:22
  • I do look at the err (hence I know this is connection / networking issue), but completely forgot you need to explicitly whitelist the heroku server on atlas ! Thanks ! :) – RRob Apr 20 '19 at 07:59
  • 3
    MongoDB Atlas forgot to mention that you have to WHITELIST your IP through their dashbaord's "Network Access" in order to connect – Ofershap Jul 28 '19 at 08:15

0 Answers0