Connecting to MongoDB via mongoose gives auth fail error

时间:2019-04-08 13:43:58

标签: node.js express mongoose

I am trying to connect to my Mongo cluster using a connection string like this:

module.exports = {
  MongoURI: MongoURI: 'mongodb+srv://philip:DummyPassword9$@test-cluster-026fd.mongodb.net/test?retryWrites=true'
}

And have set my configuration in the app.js:

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');

const app = express();

// DB Config
const db = require('./config/keys').MongoURI;

// Connect to Mongo
mongoose.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected....'))
.catch(err => console.log(err));

//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');

// Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

But instead of connecting to the Mongo cluster I get an error:

MongoError: authentication fail

I read everything that I could find online related to this problem, I tried encoding my password like this:

module.exports = {
  MongoURI: `mongodb+srv://philip:${encodeURIComponent('DummyPassword9')}$@test-cluster-026fd.mongodb.net/test?retryWrites=true`
}

But still I can't connect and I get this error. I am sure that my account password is right, what am I doing wrong?

1 个答案:

答案 0 :(得分:0)

您正在通过url连接,因此必须将密码更改为URL编码格式。
“ $” 替换为“%24” 并进行检查。
参考:HTML URL ENCODINGS