How to debug MongoError failed to connect - node.js

In the server logs after a process has been successfully connected to mongo via node 6.11.1 and mongoose 4.10.4 I started seeing this error:
MongoError: failed to connect to server [aws-us-east-1-portal.8.dblayer.com:15180] on first connect [MongoError: connection 0 to aws-us-east-1-portal.8.dblayer.com:15180 timed out]
During this time, mongoose recognized an issue:
mongoose.connection.readyState had a value of 0.
What else can I do to debug the connection issue? Is there some other way I can inspect this or figure out what's going on and how to resolve it?
The mongo database (version 3.2.10) is actually running over at compose.io and during this time the compose.io interface is showing all healthy statuses for the database.
Node: 6.11.1
Mongoose 4.10.4
MongoDB: 3.2.10

Can you try to increase timeout period like below:
const mongoose = require('mongoose');
const option = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000
};
const mongoURI = process.env.MONGODB_URI;
mongoose.connect(mongoURI, option).then(function(){
//connected successfully
}).catch(function(err) {
//err handle
});

Related

MongoDB can be connected with MongoClient but not mongoose

So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
console.log(url)
db.close()
})
everything works fine. But if I change it into
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
it gives the following error:
webpack://HappyHourWeb/./server/server.js?:29
throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
^
Error: unable to connect to database: my_database_url,
at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
at NativeConnection.emit (node:events:390:28)
at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Any help is greatly appreciated!
According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.
Mongoose accepts a dbName option that is
[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.
The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.
Also, that part of your code :
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.
As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.

MongoDB Replica Set Connection not created on server

I am using MongoDB 4.0. I have a Replica Set which run on my machine and different ports that is:
127.0.0.1:27017 (Master)
127.0.0.1:27018 (Slave)
127.0.0.1:27019 (Arbiter)
My replica name is "xdr"
Now on creating the connection on localhost in my nodejs code it will create the connection i.e
const options = {
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
autoReconnect : true
};
mongoose.connect('mongodb://localhost:27017, localhost:27018, localhost:27019/my_db?replicaSet=xdr, options);
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
Everything is fine in this on my local connection but when i will host my mongodb On seperate EC2 Instance on AWS, it will not connect to my replica set.
lets assume that my mongodb AWS IP is 12.12.13.12.
So when i will create the connection it will not be able to connect. My code is
const options = {
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
autoReconnect : true
};
mongoose.connect('mongodb://12.12.13.12:27017, 12.12.13.12:27018, 12.12.13.12:27019/my_db?replicaSet=xdr, options);
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
It will generate an error i.e ""
if I will connect without replicaset then it will connect only to primary i.e
mongoose.connect('mongodb://12.12.13.12:27017/my_db, options);
Is there anything which I am doing wrong on my code?
Have you verified that port 27017 and 27018 are open on your EC2 ?
You don't need to specify the arbitrer.
You have to inform mongo that you use a replicaset, with the replset option.
I use the following for my replicaset :
var config = {
db: "mongodb://myMasterIp:27017/myDb,mySlave1Ip:27018/myDb"
options: {
user: config.db_user,// only if you use username/password for DB authentication
pass: config.db_pass,// only if you use username/password for DB authentication
replset: {
rs_name: "MyReplicaSetName",
ssl: true,// only if you use ssl for your replicaset
sslValidate:false,// only if you use ssl for your replicaset
sslCA: myDbCertificate,// only if you use ssl for your replicaset
ca: myDbCertificate,// only if you use ssl for your replicaset
sslKey: myDbKey,// only if you use ssl for your replicaset
sslCert: myDbKey // only if you use ssl for your replicaset
},
socketOptions : {
keepAlive : 1,
connectTimeoutMS : 5000
},
server: { // only if you use ssl for your replicaset
ssl: true,
sslValidate:false,
sslCA: myDbCertificate,
ca: myDbCertificate
sslKey: myDbKey,
sslCert: myDbKey
},
auth: { // only if you use username/password for DB authentication
authdb: 'myAuthenticationDatabse'
}
}
};
mongoose.connect(config.db, config.options);

mongodb failed to connect to server [127.0.0.1:27017] on first connect

my code below
var mongoose = require('mongoose');
for(let i = 0;i<600;i++)
{
let db1 = mongoose.createConnection('mongodb://127.0.0.1:27017/abc');
db1.on('error', function(error) {
console.log("error = "+(i)+" "+error +db1);
});
db1.on('close', function() {
console.log("close = "+(i)+" "+db1);
});
db1.once('open', function() {
"use strict";
// db1.close();
});
}
I wanted to test mongodb ,the result is
error = 364 MongoError: failed to connect to server [127.0.0.1:27017] on first connect[object Object]
error = 365 MongoError: failed to connect to server [127.0.0.1:27017] on first connect[object Object]
error = 385 MongoError: failed to connect to server [127.0.0.1:27017] on first connect[object Object].......
Another question is whether the connection needs to be closed?
thanks.
Make sure that you have Mongo running on on port 27017 of the same computer that your Node app is running. To verify that, run this in the command line:
mongo localhost:27017
You don't need to close the connection and open it multiple times. You should open the connection once in your app and close it only when you want to close your app. See those answers for more datails:
Where to initialize a new database connection in nodejs?
Using mongoDB in Express routers

Mongoose gives error while connecting using mongolab uri ?

It gives the following error-
mongoose connection error: { [MongoError: connect EINVAL] name: 'MongoError', message: 'connect EINVAL' }
/home/user/Documents/oes/node_modules/connect-mongo/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
Error: connect EINVAL
at errnoException (net.js:905:11)
at connect (net.js:767:19)
at net.js:846:9
at asyncCallback (dns.js:68:16)
at Object.onanswer [as oncomplete] (dns.js:121:9)
14 Jun 18:04:11 - [nodemon] app crashed - waiting for file changes before starting...
This is a very old problem, But as no one has yet answered it.
We often see that users have problems connecting to MongoLab using the Mongoose driver. The root cause is almost always incorrect configuration of the driver, particularly around timeouts. The following is a connection example using the MongoLab-recommended driver options:
// mongoose 4.3.x
var mongoose = require('mongoose');
/*
* Mongoose by default sets the auto_reconnect option to true.
* We recommend setting socket options at both the server and replica set level.
* We recommend a 30 second connection timeout because it allows for
* plenty of time in most operating environments.
*/
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://user:pass#host:port/db';
mongoose.connect(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
// Wait for the database connection to establish, then start the app.
});
If this doesn't help, please ensure your password or username doesn't has any special character, Try to connect it via CMD first.
Hope I helped :)

mongoose output the error "Error: connection closed"

I stumble upon a curious problem about mongoose connect the mongodb, it generate the detail errors as the following
e:\Mentor_Resources\node\node_twitter_bootstrap>node app
Express server listening on port 3000
Trace: error occure when start to connect dbError: connection closed
at e:\Mentor_Resources\node\node_twitter_bootstrap\server\module\word.js:14:
17
at Connection.open (e:\Mentor_Resources\node\node_twitter_bootstrap\node_mod
ules\mongoose\lib\connection.js:201:5)
at Db.open (e:\Mentor_Resources\node\node_twitter_bootstrap\node_modules\mon
goose\node_modules\mongodb\lib\mongodb\db.js:247:16)
at Server.connect.connectionPool.on.server._serverState (e:\Mentor_Resources
\node\node_twitter_bootstrap\node_modules\mongoose\node_modules\mongodb\lib\mong
odb\connection\server.js:413:7)
at EventEmitter.emit (events.js:115:20)
at connection.on.connectionStatus (e:\Mentor_Resources\node\node_twitter_boo
tstrap\node_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connect
ion_pool.js:108:15)
at EventEmitter.emit (events.js:91:17)
at Socket.closeHandler (e:\Mentor_Resources\node\node_twitter_bootstrap\node
_modules\mongoose\node_modules\mongodb\lib\mongodb\connection\connection.js:401:
12)
at Socket.EventEmitter.emit (events.js:88:17)
at Socket._destroy.destroyed (net.js:364:10)
the code snippet of mongoose is:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/word-sentence",function(err) {
if(err)
console.trace('error occure when start to connect db' + err);
});
i am sure the mongodb is open, and i restart mongodb for several times,but the error is still exist, so I reboot my Windows XP , and try again the problem disappear,everything is ok, so I want to know why?
This is a common problem when pooled connections in longer running applications return connection closed.
The mongoose documentation recommends adding keepAlive to the options object you pass into the connect function.
Here's an example (you can remove replset if you're not using this),
// include keep alive for closing connections,
// http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
var mongoOptions =
{
db: {safe: true},
server: {
socketOptions: {
keepAlive: 1
}
},
replset: {
rs_name: 'myReplSet',
socketOptions: {
keepAlive: 1
}
}
};
mongoose.connect( YOUR_URI, mongoOptions );
mongoose.connection.on('error', function(err) {
console.log('Mongo Error:\n');
console.log(err);
}).on('open', function() {
console.log('Connection opened');
});
mongoose.connect() Is not accepting any callback functions as you have use in your code i.e.your code snippet of mongoose:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/word-sentence",function(err) {
if(err)
console.trace('error occurred, when attempted to connect db. Error: ' + err);
});
So, I recommend you to start with this:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/word-sentence');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
// yay connected!
});
Again you cannot expect any arguments in the callback from db.open('open', function cb(){})
I suggest to go through these quick start, mongoose docs - enlightens how you can jump into source code if some conflict is found in the docs & mongodb/mongoose close connection

Resources