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 :)
Related
I am trying to establish a connection to remote mongo server through ssh tunnel using mongoose
The implementation code is:
import tunnel from 'tunnel-ssh';
const config = {
username: 'username',
Password: 'password',
host: process.env.SSH_SERVER, //192.168.9.104
port: 22,
dstHost: process.env.DESTINATION_SERVER, //192.168.9.104
dstPort: process.env.DESTINATION_PORT, //27017
localHost: '127.0.0.1',
localPort: 27017
};
this is the config that i have created while the connection is as follows:
class DB {
initDB() {
tunnel(config, (error, server) => {
if (error) {
console.log('SSH connection error: ' + error);
}
const url = 'mongodb://' + process.env.MONGO_URL; //localhost:27017/DBname
mongoose.connect(url, { useNewUrlParser: true });
mongoose.plugin(toJson);
mongoose.plugin(setProperties);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
console.log('DB connection successful');
});
});
}
}
When the function initDB() is invoked the following error pops up
SSH connection error: ConfigError: host not set
events.js:183
throw er; // Unhandled 'error' event
^
ConfigError: host not set
The host is already set but this error seems to be somewhere in the config part but I doesnt seem to single out to the exact reason
your "host" property at "config" var isn't defined. try using hard coded value instead of env var, if it works it means process can't read env vars which might be caused since you R not importing dotenv module
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);
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
});
I have a simple Node.js that uses mongoose to connect with Mongo database hosted on mLab.
Everything seems working just fine: adding new records, querying for existing stuff.
Only sometimes, after some period of inactivity, when I look at the console I see the following:
events.js:160
throw er; // Unhandled 'error' event
^
Error: connection timeout
at Db.<anonymous> (___PATH___/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:168:17)
at emitTwo (events.js:106:13)
at Db.emit (events.js:191:7)
at Server.listener (___PATH___/node_modules/mongodb/lib/db.js:1786:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Server.<anonymous> (___PATH___/node_modules/mongodb/lib/server.js:274:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Pool.<anonymous> (___PATH___/node_modules/mongodb-core/lib/topologies/server.js:334:12)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (___PATH___/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
Right now it doesn't matter that much to me - I can always restart the app. I'm worried that in production it will cause a lot of headaches so I preemptively ask what's the issue here?
Note that initially everything is working fine, it after some time when I get Error: connection timeout
Sample Connection code for Mongo-Node using Mongoose
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const options = {
useMongoClient: true,
reconnectTries: 5000,
reconnectInterval: 0,
socketTimeoutMS: 100000,
connectTimeoutMS: 100000
}
mongoose.connect(mongodb://........, options);
var db = mongoose.connection;
db.on('error', function (error) {
console.log('Error while connecting to mongodb database:', error);
});
db.once('open', function () {
console.log('Successfully connected to mongodb database');
});
db.on('disconnected', function () {
//Reconnect on timeout
mongoose.connect(mongodb://........, options);
db = mongoose.connection;
});
it seems that there is fluctuation in your internet connection. Maybe this is the reason of connection timeout.
you can handle it by setting the timeout.
As below :
var timeout = require('connect-timeout');
app.use(timeout('5s'));`
in your app.js file
Replace your mongoose connection setting by this code:
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.
});
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