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
Related
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.
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 trying to connect a MongoDB atlas instance to a nodejs/express server :
const mongoose = require("mongoose");
const dbURI =
"mongodb+srv://(url copied from atlas connect)";
const options = {
useNewUrlParser: true,
dbName: "data"
};
mongoose.connect(dbURI, options).then(
() => {
console.log("Database connection established!");
},
err => {
console.log("Error connecting Database instance due to: ", err);
}
);
But I keep get the following error:
MongoNetworkError: connection 5 to cluster ... 27017 closes at TLSSocket. ...
How can I fix this?
Resolved -- Check IP whitelist!
I just added MongoDB to the dependencies of my Node.js project created with the npm init command. My index.js code is:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/mydatabase';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
But when I execute the code it throws the following error:
AssertionError: null == { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
I really don't know how to fix it. I followed some guides that reported the same error but I couldn't fix it.
Should I poen a port on my modem? Should I replace "localhost" with my IP? Should I do anything else?
Please help me!
UPDATE:
I installed a MongoDB server on my Android device and replacing the url variable with mongodb://ANDROID-DEVICE-LOCAL-IP:27017/mydatabase it now works.
How can I accomplish it placing the database on my computer? Is the firewall blocking incoming connections? Is this why it works on Android but not on Windows?
I fixed the issue!
I ran mongod -dbpath "MY-PATH" in the cmd and now it works.
The error occurred because nothing was listening on 27017 port. Now the mongod program is listening for connections on that port and so the connection from my project is no more refused.
Make a configuration file like config.js
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/cubs'
}
And require that file in your server code
var config = require('./config');
var mongoose = require('mongoose');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
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 :)