猫鼬无法连接到mLab环境

时间:2018-08-01 21:34:55

标签: node.js mongodb mongoose mlab

我有一个应用程序试图使用Mongoose连接到mLab环境。我将以下代码配置为尝试连接到mLab MongoDB实例。

mongoose.connect(process.env.MONGODB_URI);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {});

变量process.env.MONGODB_URI等于 mongodb://user:password@ds123456.mlab.com:12345/someRandomName(为隐私起义的标识符)。

适用的软件版本

节点:v10.7.0

NPM:6.2.0

猫鼬:5.2.6

当我尝试运行应用程序时,出现以下错误。

  

节点./bin/www

(node:2555) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
connection error: Error: Slash in host identifier
    at parseConnectionString (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js:219:15)
    at parseHandler (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js:129:14)
    at module.exports (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js:25:12)
    at deprecated (internal/util.js:70:15)
    at connect (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js:179:3)
    at connectOp (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js:283:3)
    at executeOperation (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/utils.js:420:24)
    at MongoClient.connect (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js:168:10)
    at Promise (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/lib/connection.js:493:12)
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/lib/connection.js:490:19)
    at Mongoose.connect (/Users/nathanielsuchy/Documents/control-panel/node_modules/mongoose/lib/index.js:230:15)
    at Object.<anonymous> (/Users/nathanielsuchy/Documents/control-panel/app.js:20:10)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)

我得出两个结论。一个我需要使用新的URL解析器,第二个是我的数据库连接字符串格式没有出现的问题。我应该如何解决该问题?

1 个答案:

答案 0 :(得分:1)

正确的格式为mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

您的密码是否包含“ @”或其他特殊字符?如果是这样:

const dbUrl = `mongodb://adminUsername:${encodeURIComponent('adminPassword')}@localhost:27017/mydb`;

也请检查以下内容:MongoDB password with "@" in it