Cannot make mongo script base shell authentication

I have a very complex problem that I can solve by writing a mongo script shell, but I can't even make a simple connection. I have a local mongo database that requires a username / password, which I usually get as follows:

mongo admin -u <username> -p 

in which I enter the password and cheers! I have a shell. but this will not work for my problem. As a test, I created a file called test.js and all that it has is:

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

Then I run the script from the command line as follows:

 mongo test.js 

at this moment i get the following:

 MongoDB shell version: 2.4.10 connecting to: test 

Why am I not getting any results?

+5
source share
1 answer

I finally did the job. Here is how I did it:

First I created 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()); } 

Then I 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 with any other developer who is having problems.

1) if you add a new database and you use mongo with authentication, you need to first enter the authentication database and then switch to the desired database (as my example shows) or you need to add a user / password to the required database (as I probably should have done first)

2) When running a javascript file through mongo, do not expect to use the same "javascript" functions that you are used to. I just learned a lesson that not all javascript is the same. for example, you cannot use Console.log () in a javascript file that runs through mongo, because console.log is actually not the main javascript, but rather a function specific to browsers and node implementations.

+8
source

Source: https://habr.com/ru/post/1204763/


All Articles