I'm in the process of setting up mongodb, and we use puppet to control the configuration of our servers.
I've got most things setup how I need them, but I need to create the user inside the mongo database.
I know how to do this using the mongo shell, and I know that I can do it using javascript / a .js using the command
db.addUser("username", "password"[, readOnly])
However, I have been unable to find a solid example of what is needed to do this in javascript. More to the point, I need to be able to add a user from the command line, using some sort of shell script.
If someone could
a) point me to some solid examples of using javascript with mongoDB and
b) how can I do this from the command line?
createUser() on the $external database to create users who have credentials stored externally to MongoDB. The value can be either: the user's password in cleartext string, or. passwordPrompt() to prompt for the user's password.
The MongoDB JavaScript (NodeJS) Driver makes it simple to work with MongoDB databases from Node. js applications. To connect to your database and run the queries discussed in this Quick Start series, you'll need the MongoDB JavaScript (NodeJS) driver.
I know AD7six has already given an issue but when I try, I obtain a user with a database authentication 'test'.
So I added one command before create User to choose this authentication database.
db = db.getSiblingDB('myDataBase');
db.createUser(
{
user: "myUser",
pwd: "myPwd",
roles: [
{ role: "readWrite", db: "myDataBase" }
]
}
);
The authentication database and the database used by the user can be different. The command "getSiblingDB(dataBase)" (Javascript) is an alternative to "use dataBase" (Shell)
Mongo's cli tells you itself how to use it with a js file
$ mongo --help
MongoDB shell version: 2.0.3
usage: mongo [options] [db address] [file names (ending in .js)]
...
usage: mongo [options] [db address] [file names (ending in .js)]
For example:
$ echo 'db.addUser("guest", "passwordForGuest", true);' > file.js
$ mongo mydb file.js
MongoDB shell version: 2.0.3
connecting to: mydb
{ "n" : 0, "connectionId" : 1, "err" : null, "ok" : 1 }
{
"user" : "guest",
"readOnly" : true,
"pwd" : "b90ba46d452e5b5ecec64cb64ac5fd90",
"_id" : ObjectId("4fbea2b013aacb728754fe10")
}
Udpate:
db.addUser deprecated since 2.6
https://docs.mongodb.com/v2.6/reference/method/db.addUser/
use db.createUser
instead:
// file.js
db.createUser(
{
user: "guest",
pwd: "passwordForGuest",
roles: [ { role: "read", db: "mydb" } ]
}
)
$ mongo mydb file.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With