2

Below is the code Snippet :

var mongoose = require('mongoose');

//mongodb://localhost/db
mongoose.connect('mongodb://username:pwd@ds117859.mlab.com:17859/db');
var db = mongoose.connection;

Now when I connect to localhost server, it works fine and I am able to perform operations on local Mongo DB But when I connect to my db on MLAB, I get the following error:

$ node app.js
Server started on port 3000
(node:8648) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Authentication failed.

When I print the error object I get this :

err { MongoError: Authentication failed.
    at C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:595:61
    at authenticateStragglers (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:513:16)
    at Connection.messageHandler (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:549:5)
    at emitMessageHandler (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:309:10)
    at Socket.<anonymous> (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:452:17)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:547:20)
  name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  errmsg: 'Authentication failed.',
  code: 18,
  codeName: 'AuthenticationFailed' }
tester9
  • 93
  • 9
  • 1
    Did you create a database username and password or are you using your account username and password? Your account username and password should not be used in a connection string. See more here: http://docs.mlab.com/connecting/#users – tfogo Jan 31 '18 at 08:37
  • 2
    Did you create an user with permissions? Not your user/pwd account, but a user for that project. Here's the docs http://docs.mlab.com/connecting/#users – Rafael del Rio Jan 31 '18 at 08:37
  • Thank you @tfogo. That was the issue. – tester9 Jan 31 '18 at 09:03

1 Answers1

0
            //replace username,password and databasename
            var mongoose = require('mongoose');
            var mongodbUrl = "mongodb://username:password@ds153869.mlab.com:53869/databasename";
            mongoose.connect(mongodbUrl,  { useNewUrlParser: true });

            mongoose.connection.on("connected", function(){
                console.log("mongoose database connected with " + mongodbUrl);
            });
            mongoose.connection.on("error", function(err){
                console.log("Unable to connect with " +mongodbUrl + "error are"+ err);
            });
sunilsingh
  • 503
  • 1
  • 5
  • 9