试图从 localhost 服务器连接 mLAB DB?身份验证失败
Posted
技术标签:
【中文标题】试图从 localhost 服务器连接 mLAB DB?身份验证失败【英文标题】:Trying to connect mLAB DB from localhost server? Authentication failed 【发布时间】:2018-07-10 04:50:17 【问题描述】:下面是代码片段:
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'
【问题讨论】:
您是创建了数据库用户名和密码,还是使用了您的帐户用户名和密码?您的帐户用户名和密码不应在连接字符串中使用。在此处查看更多信息:docs.mlab.com/connecting/#users 您是否创建了具有权限的用户?不是您的用户/密码帐户,而是该项目的用户。这是文档docs.mlab.com/connecting/#users 谢谢@tfogo。这就是问题所在。 【参考方案1】: //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);
);
【讨论】:
以上是关于试图从 localhost 服务器连接 mLAB DB?身份验证失败的主要内容,如果未能解决你的问题,请参考以下文章
mLab 连接错误:数据库名称不能有 mongodb:// 的保留字符