Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't make basic mongo shell script with authentication

I have a really complicated issue that i think i can solve by writing a mongo shell script but i can't even manage to make a simple connection. I have a local mongo database which is requires a username/password that i normally access like this:

mongo admin -u <username> -p

at which point I enter the password and hooray! i have a shell. but that won't work for my issue. As a test, I created a file called test.js and all it has in it is this:

var conn = new Mongo()

db = conn.getDB("test");
db.cust.find();

I then run the script from the command line like so:

mongo test.js

at which point i get this:

MongoDB shell version: 2.4.10
connecting to: test

Why am i getting no results?

like image 326
Dallas Caley Avatar asked Oct 15 '14 18:10

Dallas Caley


1 Answers

I finally made this work. This is how i ended up doing it:

First I made a file called test.js with the following in it:

db = connect("localhost:27017/admin");

db.auth('username','password');

db = db.getSiblingDB('test');

var cursor = db.cust.find();

while (cursor.hasNext()) {
   printjson(cursor.next());
}

I then ran this command from the command line:

mongo test.js

I also want to point out a few things that i learned while trying to do this to any other developer who is having issues.

1) if you add a new database, and your are running mongo with authentication you either need to log into the authentication database first and then switch to the desired database (as my example shows) or you need to add a user/password to the desired database (as i probably should have done in the first place)

2) When running a javascript file via mongo, don't expect to use the same "javascript" functions that you are used to. I just learned a hard lesson that not all javascript is the same. for example, you can not use Console.log() in a javascript file that is run via mongo because console.log is not actually core javascript but rather a function specific to browser and node implementations.

like image 147
Dallas Caley Avatar answered Sep 20 '22 14:09

Dallas Caley