Can connect only when I don't specify db name

I am trying to secure my mongodb installation. I created a user as follows:

db.createUser(
  { 
  user: 'username',
  pwd: passwordPrompt(), 
  roles: [ 
    { role: "readWrite", db: "db1" }, 
    { role: "readWrite", db: "db2" } 
  ] 
})

I can connect by doing:

mongosh "mongodb://username@localhost"

However the following fails with the message Authentication failed.:

mongosh "mongodb://username@localhost/db1"

Ok, I figured it out. I needed to do use db1 before adding the user to db1.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.