1

When I run the following script:

mongo -u root myinitscript.js

And myinitscript.js has the following code:

use somedbname
db.createUser({
    user: 'someuser',
    pwd: 'somepass',
    roles: [{
        role: 'dbOwner',
        db: 'somedbname'
    }]
});

Produces the following error:

MongoDB shell version v4.4.0
Enter password: 
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("352e2ff4-3c4b-4e4c-b898-b67450c13627") }
MongoDB server version: 4.4.0
uncaught exception: SyntaxError: unexpected token: identifier :
@mongodb_init.js:1:4
failed to load: mongodb_init.js
exiting with code -3

When I remove use somedbname from the script - it works, but does NOT create the database, which is my primary goal. Running use somedbname under mongo shell works just fine, but is NOT an automation. Any hints on how to solve this?

1 Answer 1

3

use dbname is a special shell helper. When you load a js file you can't use this helper because its syntax is not valid js.

Use getSiblingDb instead in js files.

You can also use the connection string (mongodb:// URI) as the shell argument and include the database in the connection string.

Sign up to request clarification or add additional context in comments.

1 Comment

The working version of the script is: db = getSiblingDB('somedbname'); db.createUser({ user: 'someuser', pwd: 'somepass', roles: [{ role: 'dbOwner', db: 'somedbname' }] }); @D. SM, thank you very much for saving my day!!! PS. I'm using a docker image for mongo, so I do NOT control the way they setup the connection string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.