问题
const express = require('express');
const app = express();
const mongoose = require('mongoose');
require('./models/users');
require('./services/passport');
const authRoutes = require('./routes/authRoutes');
const Keys = require('./config/dev');
authRoutes(app);
mongoose.connect(Keys.MONGOOSE_URI);
const port = process.env.PORT || 5000;
app.listen(port);
I have a node express application and I trying to connect to mlab db using mongoose. I am getting following exception:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [ds111598.mlab.com:11598] otworkError: connect ECONNREFUSED 35.168.9.109:11598]
Tech stack I am using:
"mongoose": "^4.11.1",
node: 6.11.1
npm: 4.6.1
I have tried using the latest mongoose version as well but still the same issue. I am stuck because of this. Can anybody help in this?
Thanks
回答1:
If you are under corporate proxy, you must have to come out else you can check my code.
const options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: 100, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
mongoose.connect('mongodb://user:xxxxxx@dsxxxx.mlab.com:667799/DB_NAME',options).then(
()=>{
console.log("connected to mongoDB")},
(err)=>{
console.log("err",err);
}
)
回答2:
SOLUTION
I just ran into this same problem, and spent several minutes trying to debug and get a successful workaround.
But very easily I was able to solved it.
The issue for getting authentication error is because one does not have yet created a user on mlab that would be connected to mongo remotely.
Creating a db successfully on mlab is not the last step before reverting back to text editor to connect to mongo via provided url on mlab page.
ONE HAS TO CREATE A USER UNDER 'USERS' tab on mlab which is located on database's details page.
Add the credentials then to create a user, and then finally add these credentials in the mlab-provided mongo url.
And walla! YOU ARE CONNECTED.
回答3:
Create a new User and more importantly, ensure that password for the user contains only Alphanumeric. No special characters like . # ,
e.t.c
回答4:
I solved this issue by not using a '.' in the db username. This isn't clear but it fixed my issue.
来源:https://stackoverflow.com/questions/48418636/mongoose-to-mlab-connection-issues-unhandledpromiserejectionwarning-unhandled