试图从localhost服务器连接mLAB DB?验证失败

时间:2018-01-31 06:44:44

标签: json node.js mongodb api mlab

以下是代码段:

var mongoose = require('mongoose');

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

现在当我连接到localhost服务器时,它工作正常,我可以在本地Mongo DB上执行操作 但是当我在MLAB上连接到我的数据库时,我收到以下错误:

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

当我打印错误对象时,我得到了这个:

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' }

1 个答案:

答案 0 :(得分: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);
            });