Search code examples
javascriptmongodbopenshiftmongodb-shell

Error Running MongoDB Script on OpenShift Gear


I wrote a database population script (in JavaScript) so that I could easily run it on my local and on the server. I want to run it from the command line so that all I have to do is push it to the server/gear and execute it. The script runs fine on my local, but when I try to run it on the OpenShift gear it gives the following error:

MongoDB shell version: 2.4.9
connecting to: 127.XX.XXX.X:27017/admin
Sat Sep 12 12:20:25.979 count failed: { "ok" : 0, "errmsg" : "unauthorized" } 
at src/mongo/shell/query.js:180
failed to load: ./Create.js

I'm trying to execute the command:

[xxxxxx-xxxxxx.rhcloud.com scripts]\> mongo ./Create.js

I have included the innards of my file. I left out all the document creation stuff. Just know I added document to an array.

// Switch to the DB we want
var connection;
try {
    // Try to connect to local first
    connection = new Mongo();
}
catch(err) {
    // If error, connect to OpenShift server
    connection = new Mongo('127.XX.XXX.X:27017');
}

db = connection.getDB('xxxxxxx');

// Create array to store documents
var newDocs = [];

...
// Documents are added to newDocs here
...

// If any new documents exist, insert them
if(newDocs.length) {
    var bulk = db.xxxxxxx.initializeUnorderedBulkOp();

    newDocs.forEach(function (doc) {
        bulk.insert(doc);
    });

    bulk.execute();
    print('NEW DOCS INSERTED');
}
else {
    print('NO NEW DOCS');
}

Solution

  • I used db.auth('username', 'password'); to authenticate. Ultimately, I added a variable to the script to track if I was running the script locally or on the server. Then I used a variable for the password so that I wouldn't have the DB password just hanging out in the script. I pass the password in from the command line with the --eval option. Here is the altered head of the script:

    // Switch to the DB we want
    var connection;
    var isLocal = true;
    try {
        // Try to connect to local first
        connection = new Mongo();
    }
    catch(err) {
        // If error, connect to OpenShift server
        connection = new Mongo('127.XX.XXX.X:27017');
        isLocal = false;
    }
    
    db = connection.getDB('xxxxxxx');
    
    if(!isLocal) {
        // If on server, authenticate
        db.auth('username', password);
    }
    
    // Create array to store documents
    var newDocs = [];
    

    Then, to run the script from the command line on the server, I use the following:

    mongo --eval "var password = 'xxxxxxx';" Create.js