How using MongoDB shell define function and use it?
In a script file createusers.js there is following code to create a user with read role on specific database.
function createReader(database, username, password)
{
db.getSiblingDB(database).createUser({
user : username,
pwd : password,
roles : [ { role : "read", db : database } ]
});
}
Is there possibility to execute this function in mongodb shell? The following call doesn't succeed
mongo --eval="createReader('somedb', 'user1', 'pass1')" createusers.js
gives error createReader is not defined.
You can use load() to load the js file from eval:
mongo --eval "load('createusers.js'); createReader('somedb', 'user1', 'pass1')"
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