linuxmongodbazure-resource-managermongo-shell

Using mongosh to create users and database automatically


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.


Solution

  • 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