10

Connects without a hitch, but on insert() throws me this error.

var MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var url = 'mongodb://____:____@ds125565.mlab.com:25565/heroku_w268n9pj';

MongoClient.connect(url, function(err, client) {
    assert.equal(null, err);
    db = client.db('temp');
    console.log("connected!");
    const collection = db.collection('temp');
    collection.insert([{
        something: please
    }
});

I saw some other answers regarding mLab accounts and credentials, but I just created a new admin account for this. Frustrating because it was working previously with v2.3.

user61871
  • 929
  • 7
  • 13
  • same error with mongo shell or with pymongo – mirt Dec 26 '17 at 14:47
  • 17
    Hey, don't know if you've solved this yet, but that connection string looks like a Sandbox plan. You only have access to one database on Sandbox plans. The database name in your connection string is `heroku_w268n9pj`. so try `db = client.db('heroku_w268n9pj')`. Otherwise, you're trying to run commands on the `temp` database - which you do not have access to. – tfogo Dec 31 '17 at 16:34
  • 1
    The reason this worked with 2.3 but not 3.0 is in 2.3 the `db` object was created automatically from the connection string. Whereas now you need to specify the db name yourself. Make sure it's the same one as in the connection string. – tfogo Dec 31 '17 at 16:36
  • Both suggestions work. – jm18457 Jun 27 '18 at 20:05
  • 2
    @tfogo Would be nice to post this as answer :-) – Knut Holm Jul 13 '18 at 12:42
  • 1
    @tfogo, please, could you post a full reply with an example of what you said ? – realtebo Jan 13 '19 at 19:12
  • @tfogo, please, write the answer, I wanna give +10 reps for you, u saved my hours =) – Yegor Oct 05 '19 at 22:43

1 Answers1

1

When attempting to connect to an mlab database, you have to correctly specify the client. It's located at the end of your connection string, just after the final forward slash.

mlab_url = "mongodb://db_user_name:db_password@ds139725.mlab.com:39725/heroku_sd1fp182?retryWrites=false"
client = MongoClient(url)


db = client["heroku_sd1fp182"]
collection = db["coinHack"]

You may also get the error:

This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.

Just add "?retryWrites=false" to your connection string, as shown above.

Dr. Div
  • 951
  • 14
  • 26