Play + ReactiveMongo - How to create database and add user using ReactiveMongo

91 views
Skip to first unread message

binoy...@gmail.com

unread,
Feb 4, 2016, 5:32:31 PM2/4/16
to ReactiveMongo - http://reactivemongo.org
I am writing a Play Mongo app using reactivemongo.

I am trying to create a new database on demand and add a user to it. I have not seen any examples that show how to execute a system command. 

Can anybody please give me a lead into it ?

Cédric Chantepie

unread,
Feb 5, 2016, 5:07:19 PM2/5/16
to ReactiveMongo - http://reactivemongo.org
Why would you need to create DB in this way?

binoy...@gmail.com

unread,
Apr 26, 2017, 2:24:05 PM4/26/17
to ReactiveMongo - http://reactivemongo.org

Need to create an administration app for Mongodb. Can you  please guide how I can create database and add authenticated users to it using ReactiveMongo ?

Cédric Chantepie

unread,
Apr 27, 2017, 3:16:24 AM4/27/17
to ReactiveMongo - http://reactivemongo.org
What have you already tried?

binoy...@gmail.com

unread,
Apr 27, 2017, 12:47:38 PM4/27/17
to ReactiveMongo - http://reactivemongo.org

This is my current code 

def makeNewDb(dbName: String, dbUser: String, dbPass: String): Try[BSONDocument] = {

 
val checkUri: Try[ParsedURI] = MongoConnection.parseURI(config.getString("admindb.uri").get)

 
val database: Future[DefaultDB] = reactiveMongoApi.driver.connection(checkUri.get).database("admin")

 
val createUsrCmd = BSONDocument("createUser" -> dbUser, "pwd" -> dbPass,
    "roles" -> BSONArray(BSONDocument("role" -> "readWrite", "db" -> dbName)))

 
val runner: CommandWithPackRunner[BSONSerializationPack.type] = Command.run(BSONSerializationPack, FailoverStrategy.default)

 
val defDb: DefaultDB = Await.result(database, Duration(5, TimeUnit.SECONDS))
 
val siblingDb: DefaultDB = defDb.sibling(dbName)

 
val create = siblingDb[BSONCollection]("deleteme").create()

  val one: Future[BSONDocument] = runner.apply(siblingDb, runner.rawCommand(createUsrCmd)).one(ReadPreference.primaryPreferred)

 
val result: Future[Try[BSONDocument]] = one map (document => {
   
if (document.contains("errmsg")) {
     
val errMsg: String = document.getAs[String]("errmsg").get
     
LOG.error(s"Failed to add new user ${dbUser} for the database: ${errMsg}")
     
Failure[BSONDocument](new Error(errMsg))
   
}
   
else {
     
LOG.debug(s"Successfully finished adding new user ${dbUser} for the database: ${dbName} ")
     
Success[BSONDocument](document)
   
}
 
})

 
Await.result(result, Duration(3, duration.SECONDS))
}

It seemingly does not work. A new db is not created after execution of this  code





On Thursday, April 27, 2017 at 3:16:24 AM UTC-4, Cédric Chantepie wrote:
What have you already tried?

Cédric Chantepie

unread,
Apr 27, 2017, 5:45:07 PM4/27/17
to ReactiveMongo - http://reactivemongo.org
Reply all
Reply to author
Forward
0 new messages