I am building a nodejs app using expressjs framework. I would like to ask how do we connect to mongodb using monk? i found this code online however it seems that we do not need to specify username and password. why is that so?
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
Appreciate any advice.
There are two methods of passing username/password:
// first:
var db = monk('USERNAME:PASSWORD@localhost:27017/nodetest1');
// second:
var db = monk('localhost:27017/nodetest1', {
username : 'USERNAME',
password : 'PASSWORD'
});
It's not very well documented, but since monk
uses mongoskin
, you can look here for more information.
I want to add an alternative to the answers above as neither worked for me.
So the way I was able to connect to a mongod --auth
instance was:
1.Make sure you create a user while logged into mongodb as a user with appropriate permissions to create users on databases (like a user with the role userAdminAnyDatabase
). If you don't have a user with this role restart mongo with just mongod
without --auth
and login as your superuser (if you have one) or with a simple mongo
command and make this user with the appropriate privileges.
I highly recommend reading up on mongodb roles here: http://docs.mongodb.org/manual/reference/built-in-roles/
2.Once you are logged into your database instance with the appropriate user who is supposed to be creating other users, type use db_name
where db_name is the name of your database that you want to make the user for.
3.Once inside this database use the db.createUser command like so: db.createUser({user:"your_username", pwd:"your_password", roles:["your_role"]})
It's documented here: http://docs.mongodb.org/manual/reference/method/db.createUser/
4.Then just use db = monk('USERNAME:PASSWORD@localhost:27017/DATABASE_NAME')
in your code.
After you've done this you should be able to log into a running mongod --auth instance with a user for the particular database you created that user for.
For anyone curious I'm developing a little web app in Koa. Using monk and co-monk.
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