jcollum
jcollum

Reputation: 46579

how to add a user to mongo from Rails (console or rake)?

I'd like to do the equivalent of:

mongo --port 27xxx
use admin
db.addUser("venkman", "StayPuft!1")

But I'd like to do it as part of my rake db:seed. Seems like something you'd want to to with a fresh database. I thought that some variant of this:

Mongoid.database.eval('use admin; db.addUser("venkman", "StayPuft!1")' )

would do the trick, but I'm not having much luck with it:

Mongo::OperationFailure: Database command '$eval' failed: (errmsg: 
  'compile failed: JS Error: SyntaxError: missing ; before statement nofile_a:0'; ok: '0.0').
    from /home/user/.rvm/gems/ruby-1.9.2-p290/gems/mongo-1.5.2/lib/mongo/db.rb:520:in `command'
    from /home/user/.rvm/gems/ruby-1.9.2-p290/gems/mongo-1.5.2/lib/mongo/db.rb:407:in `eval'

I can get a function like this to work:

irb(main):023:0> Mongoid.database.eval(' function() { return 3+3; }' )
=> 6.0

So it seems that database.eval is not the right thing to use for scripting db admin tasks. Reasonably sure this issue isn't related to mongoid, from the stack trace. Is there something that I can use to script a user create as part of my rake db:seed?

Upvotes: 0

Views: 1171

Answers (1)

Ren
Ren

Reputation: 678

The eval fails because the javascript code is executed in the context of the database server, not the client shell. I am not totally sure, but I don't think you can do what you want with Mongoid alone.

However, if you use the Ruby driver, the code will look like this:

# set host and port with appropriate values
admindb = Mongo::Connection.new(host, port)['admin']
admindb.add_user("venkman", "StayPuft!1")

Having said that, I would not recommend putting hard coded passwords in your code were everybody can see it...

Upvotes: 1

Related Questions