skip to Main Content

Im currently using an armtemplate to create a Linux VM with MongoDB installed. Ive been using mongo script earlier for the version 4.4 of MongoDb. But we want to now start installing 6.0. In this version Mongo no longer is a part of the installation, and we are forced to use Mongosh.
Earlier the script we used is as follows:

mongoScript="db = db.getSiblingDB('$userDatabase');db.dropUser('$userName');db.createUser({ user: '$userName', pwd: '$userPassword', roles: [ { role: 'readWrite', db: '$userDatabase' } ] });"

mongo --username $adminUsername --password $adminPassword --eval "$mongoScript" admin

But now im trying to write using Mongosh

mongoScript="db = db.getSiblingDB('$userDatabase');db.dropUser('$userName');db.createUser({ user: '$userName', pwd: '$userPassword', roles: [ { role: 'readWrite', db: '$userDatabase' } ] });"

mongosh --username $adminUsername --password $adminPassword --eval "$mongoScript" admin

And im narrowed the issue to be the
db.dropUser('$userName')

Since the user doesn’t exist in the database it throws an error "MongoshInvalidInputError: [COMMON-10001] Invalid database name:"

So if i remove that part from the script it will work fine. But on some occasions I would like to run the script multiple times. But if i dont have the db.dropuser part. Then it will throw and error informing that the user already exists. Does anyone have a solution?

Hoping to create the Mongo database with the help of Mongosh script the same way as I did with Mongo script.

2

Answers


  1. Chosen as BEST ANSWER

    I adjusted it to run two script instead, One that checks if the user exists. If it does it delete that user, and then the other scripts creates it again.

    mongoScriptDropUser="db = db.getSiblingDB('$userDatabase');if (db.getUser('$userName') != null) db.dropUser('$userName');"
    
    mongoScript="db = db.getSiblingDB('$userDatabase');db.createUser({ user: '$userName', pwd: '$userPassword', roles: [ { role: 'readWrite', db: '$userDatabase' } ] });"
    
    
    mongosh --username $adminUsername --password $adminPassword --eval "$mongoScriptDropUser" admin
    
    mongosh --username $adminUsername --password $adminPassword --eval "$mongoScript" admin
    

  2. Why do you drop the user? Check if the user exist, before you create it. Run something like this:

    if (db.getUser('$userName') != null) db.createUser({ user: '$userName', pwd: '$userPassword', roles: [ { role: 'readWrite', db: '$userDatabase' } ] });
    

    I did not test it, perhaps you have to use

    db.getUsers({ filter: { user: '$userName' } })
    

    or

    db.runCommand({ usersInfo:  { user: '$userName', db: '$userDatabase' } })
    

    or

    db.getUser('$userName').ok != 1
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search