can't make basic mongo shell script with authentication

后端 未结 1 1517
执笔经年
执笔经年 2021-02-13 09:19

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 w

相关标签:
1条回答
  • 2021-02-13 10:03

    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.

    0 讨论(0)
提交回复
热议问题