mongoose: `authdb` option not working

using

    var connectionString = 'mongodb://' + config.database.username + ':' + config.database.password + '@' + config.database.host + ':' + config.database.port + '/' + dbname;
    var connection = mongoose.createConnection(connectionString);

everything is replaced fine. user is create via mongo shell db.addUser() and has role ‘readWriteAnyDatabase’. User can connect via mongo shell and query the db. But not via mongoose.

    MongoError: not authorized for query on punch.shops
    >>     at Object.toError (/var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js:110:11)
    >>     at /var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:634:54
    >>     at Cursor.close (/var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:903:5)
    >>     at commandHandler (/var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:634:21)
    >>     at /var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1670:9
    >>     at Server.Base._callHandler (/var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:382:41)
    >>     at /var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:472:18
    >>     at MongoReply.parseBody (/var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
    >>     at null.<anonymous> (/var/www/virtual/punch/html/punch/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:430:20)
    >>     at EventEmitter.emit (events.js:95:17)
    >> Exited with code: 8.

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 25

Most upvoted comments

After hours of debugging I found the solution: use the authdb option.

     var opt = {
            user: config.database.username,
            pass: config.database.password,
            auth: {
                authdb: 'admin'
            }
        };

        var connection = mongoose.createConnection(config.database.host, 'mydatabase', config.database.port, opt);

For some reason I am able to connect to the admin database and create records with no problems.

This is how I am connecting:

var options = {
   user: USER,
   pass: PASS,
   auth: {
       authdb: 'admin'
   }
};

var db = mongoose.connect('localhost', 'database', 28017, options);

Actually, looks like authdb option should work. Can you try connecting using the mongodb URI syntax, that is:

mongoose.connect('mongodb://[USER]:[PASS]@localhost:28017?authSource=admin');

Also, can you double check that you’re connecting to the right port and using the right password for the admin.root user?