Nodejs Mongoose Error: getaddrinfo ENOTFOUND undefined undefined:27017 - node.js

I'm trying to switch to mongoose from using just the native mongodb and having some trouble.
Connecting to the db as I did previously works fine:
var db;
var passDb = function(req, res, next) {
if (!db) {
mongo.connect(process.env.MONGOLAB_URI, function(err, database) {
if (err) throw err;
db = database;
req.db = db;
next();
});
} else {
req.db = db;
next();
}
}
But the way I'm trying to do it now throws an error:
var mongoose = require('mongoose');
var Poll = require('./app/models/poll');
mongoose.connect(process.env.MONGOLAB_URI);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
The error:
connection error: { [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017
]
name: 'MongoError',
message: 'getaddrinfo ENOTFOUND undefined undefined:27017' }
Any ideas what is causing this?
edit: it works when I use the database uri directly, but not when I use the environment variable. I have checked and triple checked that everything is typed correctly, it refuses to use the environment variable and I have to put it directly in the code :S

Ok, I figured out my mistake, I was connecting to the database before calling require('dotenv').load();. Mystery solved!
mongoose.connect(process.env.MONGOLAB_URI); now works!

adding directConnection=true to connection string worked for me
mongoose.connect("MONGO_URI=mongodb://localhost:27017/test-db?directConnection=true
");

i think you forget to define the env variable
or maybe you forget to call config method of dotenv packages on server or starter file
config it
const dotenv = require("dotenv")
dotenv.config()
on your watched file or starter...
then use process.env.VARIABLE
or for testing you mongo connection use simple string url
like that :
mongodb://localhost:27017/database_name

Related

TypeError: Cannot read property 'on' of undefined in node js and mongoose

I am getting an error when i run my application.
The error:
MongoDB.on('error', function(err) { console.log(err.message); });
TypeError: Cannot read property 'on' of undefined
...
I tried to comment that part of the code out to see if i have anymore similar errors and found another same one. ( This time the word "once" )
The code:
var mongoURI = "mongodb://localhost/chatapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
It would be really great if anyone could help me solve this :(
I searched the internet and found nothing helpful.
var mongoose = require('mongoose');
var mongoURI = "mongodb://localhost/chatapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
also before running the application in your terminal type npm install mongoose --save
Try this:
const mongoose = require('mongoose');
mongoose.connect(mongoURI);
mongoose.connection.once('open',()=>{
console.log('Connected to db');
});
The message is pretty clear. MongoDb is undefined.
Speaking on your MongoDb variable. Should be mongoDb with lowercase. It is one instance.
Anyway, the problem is in mongoose.connect(mongoURI).connection. Debug from there.
const config = require('../config');
const Mongoose = require('mongoose');
Mongoose.connect(config.dbURI);
Mongoose.connection.once('open',()=>{
console.log('Connected to db');
});
it helps me.

Node.js - Mongoose not accessing DB in included package

I have started working of late on MEAN technologies;
I have a module myModule. It has routes, services, models accessing database.
I have created another project, myAnotherModule in a separate directory, and have "npm link" ed it into myModule. While I try to use Mongoose in myAnotherModule, it is unable to access DB with proper credentials.
In the following code in myAnotherModule,
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new grid(db, mongoDriver);
it does not find the mongoose.connection.db and db is undefined.
Whereas if I use these lines in myModule, then the code works fine.
Why is myAnotherModule not able to find mongoose.connection.db?
How does npm link work?
Try to connect following way :
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("h");
});
exports.test = function(req,res) {
res.render('test');
};
I happened to encounter this issues recently as well. Typically people separate db config thus cause this problem. Try to declare in proper block that ensures mongodb is already connected.
db.once('open', function callback () {
var gfs = new grid(mongoose.connection.db, mongoDriver);
});

NodeJS Mongoose handle database connection failed exception

I'm building a restful web service api using NodeJS.It uses Mongoose as ODM and using MongoDB for backend.
Below i will explain my scenario
I started nodejs server
After that i shutdown the MongoDB database.
Then call the GET api call,it doest catch any errors and api call get hang.
database config in main.js file
var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb';
mongoose.Promise = global.Promise;
var options = { server: {socketOptions: { keepAlive: 300000, connectTimeoutMS: 10000 } } } ;
mongoose.connect(uri,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'connection refused !!!!!'));
db.once('open', console.log.bind(console,'connection success !!!!!'));
this is my basic GET call
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var rootRes = require('../model/rootresources.js');
router.get('/', function(req, res, next) {
rootRes.find({},function (err, rootResource) {
if (err){
console.log('Error occurd !!!') }
res.json(rootResource);
});
});
Even database connection failed, the code does not goes to error block. So didn't capture the database refuse when database connection is failed in the API call.
I want to capture that error and send internal server error (code:500) to client. I tried to find the solution but still could not find it
Any solutions or do i made a mistake ?
Thank you
Amila
Did you put the two parts of code in the same file(ie. main.js) or two different files.
put them in the same file, and run node main.js do throw exceptions.
// main.js
var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb';
mongoose.Promise = global.Promise;
var options = { server: {socketOptions: { keepAlive: 300000,
connectTimeoutMS: 10000 } } } ;
mongoose.connect(uri,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'connection refused !!!!!'));
db.once('open', console.log.bind(console,'connection success !!!!!'));
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var rootRes = require('../model/rootresources.js');
router.get('/', function(req, res, next) {
rootRes.find({},function (err, rootResource) {
if (err){
console.log('Error occurd !!!') }
res.json(rootResource);
});
});
exceptions are:
connection refused !!!!! { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
etc...
So, I think maybe you put codes about express in a file like index.js and codes about mongoose connection in another file. And just run node index.js in command line. While running codes in index.js will not include codes in other files, codes in main.js will not be executed. As the result, there is no error info.
Updates
Two ways of I know two ways of doing this:
1.In main.js create function which creates connection to database and returns a instance of db so that you can call it function in you main code.
// main.js like this
var mongoose = require('mongoose');
function createConnection(url) {
mongoose.connect(url,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'refused !!!!!'));
db.once('open', console.log.bind(console,'success !!!!!'));
return db;
}
// export function
module.exports = createConnection;
// in your index.js
var createConnection = require('./main.js');
var db = createConnection(url);
// other codes here
2.Using require or vm to compile and run javascipt code. You can find vm api detail here
//main.js
var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb';
mongoose.Promise = global.Promise;
var options = { server: {socketOptions: { keepAlive: 300000,
connectTimeoutMS: 10000 } } } ;
mongoose.connect(uri,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'connection refused !!!!!'));
db.once('open', console.log.bind(console,'connection success !!!!!'));
// index.js
// require will load file and execute automaticly
var scriptSrc = require('./main');
// other codes here
You can think of the second way as using eval('var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb'; etc...)
mongoose connection do not happen unless you hit a request. so its best you handle it in your first request middleware. see code insight bellow.
module.exports = function () {
return function (req, res, next) {
mongoose.connect(URL, MONGO_OPTIONS);
mongoose.connection
.once('open', () => { })
.on('error', (error) => {
res.status(401).json({});
});
...
Then pass the middleware above to your router: let me know if you need more explanation
router.get('/', myMiddleware(){})

heroku/dokku mongodb connection error

I've searched the Internet but couldn't find an answer for my problem. It seems specific to my application, but hopefully not :)
This error occurs both during heroku deployment as well as during dokku deployment.
But to the point.
I have the app.js file which part responsible for db connection looks like this:
/**
* DB connection
*/
var dbUrl;
if(app.get('env') === 'development'){
dbUrl = process.env.MONGOLAB_URI || "mongodb://localhost:27017/test";;
}
var db = require('./database');
db.connect(dbUrl, function(err){
if(err) {
console.log('Unable to connect to MongoDB');
} else {
console.log('MongoDB connected successfully!');
}
});
I'm working on development environment only, so I've removed the production bits.
As you can see, I'm getting dbUrl from heroku environment variables, then I'm requiring db index file which looks like this:
var MongoClient = require('mongodb').MongoClient;
var state = {
db: null
};
exports.connect = function(url, done) {
if(state.db) return done();
console.log("trying to connect to mongodb");
console.log(url);
MongoClient.connect(url, function(err, db){
console.log("mongodb callback");
if(err) return done(err);
state.db = db;
done();
});
};
And than I'm invoking the db.connect method in the app.js file (first code snippet) from the database index file (just above).
And I'm getting this error:
Starting process with command NODE_ENV=development node
server/bin/www
mongodb://user:password#ds011111.mongolab.com:33333/db_name
trying to connect to mongodb <<---- this is console.log from my db.connect method
/app/server/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)
State changed from starting to crashed
The error occurs only during heroku or dokku deployment.
My db connection is 100% correct (all the environment variables are ok as well so please don't ask about it), checked it in shell, as well as connecting to it from my localhost within the app.
Basically it works on my localhost, I've deployed it on vps with ubuntu, end it works as well. The problems occurs only when I'm trying to use automation tools.
Any help greatly appreciated
Thanks!

Why am I getting error "Trying to open unclosed connection."?

I am trying to connect my node app to mongodb via mongoose. It seems to be working, as I can add documents, but I get the error { [Error: Trying to open unclosed connection.] state: 2 }.
I created a very simple app, just to make sure everything is working properly before connecting my actual app.
Here is my simple app:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var timeSchema = new Schema({ timestamp: String });
var Time = mongoose.model('Time', timeSchema);
mongoose.connect('mongodb://localhost/mydb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function () {
var testA = new Test({ timestamp: Date() });
});
I also tried adding db.close() to the end, but it made no difference.
This is running on a Ubuntu 14.04 VPS with:
Node.js v0.10.3
MongoDB 2.6.3
Mongoose 1.4.21
In my opinion, you are trying to create another connection without closing the current one. So, you might want to use:
createConnection() instead of connect().
In your case, it would look like this:
db = mongoose.createConnection('mongodb://localhost/mydb');
I had the same issue and found that I had the below connection in another file, which was the reason why I couldn't connect with a different database name. The below createConnection is needed:
db = mongoose.createConnection('mongodb://localhost/mydb');
What I had in another file:
db = mongoose.Connection('mongodb://localhost/mydb');
just use mongoose.connect('...'); once.
maybe in your root app.js or index.js file, not in every model or database related files if your are importing (including) them.
Anyways, if you still have doubt you can check it by:
var mongoose = require('mongoose');
var db = mongoose.connection;
db.once('connected', function() {
console.log('mongoDB is connected');
});
shouldn't your
db.once('open', function () {
var testA = new Test({ timestamp: Date() });
});
be
db.once('open', function () {
var testA = new Time({ timestamp: Date() });
});
If "Test" is a different schema based on a different connection, that might affect i think
I had the same issue, but it was due to a typo:
express-sessions instead of express-session

Resources