Mongoskin Connection Fails (Error: connection closed) - node.js

I'm totally new with all the technologies I'm trying to do this with, but I have what seems like some simple code (gleaned from a tutorial) that I just can't get to work. I'm using Node, Express and Mongoskin/MongoDB. Whenever I try any operation against the db, I get a very generic "connection closed" error. I've got MongoDB 2.4.6, Mongoskin 0.6.0 and Mongo Native 1.3.19. MongoDB is running and I can connect from the terminal and work with my db. I see in the Mongo logging that my code never even establishes a connection. I thought maybe I need to call open explicitly, but even that returns the same error.
I'm sure I'm doing something dumb, but I'm stumped and help would be appreciated. Here's the code:
var express = require("express");
var mongoskin = require("mongoskin");
var db = mongoskin.db("localhost:28017/test", { safe: true, auto_reconnect: true });
var app = express();
app.get("/", function(request, response){
db.collection('testResult').find(function(error, result){
if (error) {
response.send("Find failed: " + error);
}
else {
response.send("got it ");
}
});
});
app.listen(8888);

Yep. I was doing something dumb. Just in case this is helpful for any other noob... The http client runs on port 28017 but MongoDB itself is actually listening on port 27017. Note the "7" in the second position. Duh. The right connection parameter (in my case), then, would be "localhost:27017/test".

Related

mLab doesn't work on Heroku

I've added mLab to my Heroku app, I also use mongoose. I tried use connection string from localhost, and it was working(almost). In my server file I use:
var db = mongoose.connection;
if (process.env.MONGODB_URI) {
mongoose.connect('mongodb://heroku_fb82r7lw:bbgj8uliam1psdda88fleu55li#ds161580.mlab.com:61580/heroku_fb82r7lw');
// mongoose.connect(process.env.MONGODB_URI);
} else {
mongoose.connect('mongodb://heroku_fb82r7lw:bbgj8uliam1psdda88fleu55li#ds161580.mlab.com:61580/heroku_fb82r7lw');
// mongoose.connect('mongodb://localhost/fitMe')
}
If I open the app from localhost, it saves things to the db, and can get it back, although not everything, but on heroku it doesn't work at all. I use react with server. I think that something wrong with the routs.. so here is the link to server file :
https://github.com/HelenaVolskaia/Motivation/blob/master/server/app.js
You can set an env variable locally and only use this:
// Connect Mongo
mongoose.Promise = global.Promise; // mongoose promises deprecated, use node - mongoosejs.com/docs/promises
mongoose.connect(config.db.MONGODB_URI);
mongoose.connection.once('open', () => { console.log('MongoDB Connected'); });
mongoose.connection.on('error', (err) => { console.log('MongoDB connection error: ', err); });
But regardless, add the on connection error handler and see what the error is, so you can dig deeper into why it's not connecting.

Mongoose never returns its promise when I try to connect to the same db using a working URL

I have a locally hosted mongodb that I can connect to using mongodb.MongoClient.
Working code:
var mongoClient = require("mongodb").MongoClient;
...
var startApp = function(db) {
// Get our collections in an easy to use format
var database = {
chats: db.collection('chats'),
messages: db.collection('messages')
};
// Configure our routes
require('./app/routes')(app, database);
// START APP
// Start app on port
app.listen(port);
// Tell user the app is running
console.log("App running on port " + port);
// Expose app
exports = module.exports = app;
}
// DATABASE
var database = null;
mongoClient.connect(config.url, function(err, returnDB) {
if(err) {
console.log(err);
} else {
console.log("DB connected");
startApp(returnDB);
}
});
Legacy code that no longer works:
var mongoose = require('mongoose');
...
// Connect to DB
console.log('Connect to database (' + db.url + ')');
mongoose.connect(db.url);
I have added a callback to this connect method but it never gets called (error or no error, this connect function never gets to my callback).
This entire legacy app relies on the API using mongoose to talk to the database so I do not want to redo it all using mongodb. How can I fix this?
*config.url and db.url are loaded from the same file and it is a valid and running mongodb.
It was really easy to fix. Thanks #Bhavik for asking me what version I was using.
I updated mongoose to 4.8.1 by specifying the newest version in packages.json and the issue is resolved.

Mongoose never connects to mongodb

I'm trying to connect to MongoDB using Mongoose on an Amazon EC2 Linux server.
Here's my code:
var mongoose = require('mongoose');
console.log("Attempting antyhing to do with mongoose"); //shown
var db = mongoose.connection;
db.on('error',console.error.bind(console,'db connection error:')); //not shown
db.once('open',function(){
console.log("Successful connection to db!"); //not shown
});
mongoose.connect('mongodb://localhost:27017/local',function(err){
console.log("some kinda connection made"); //not shown
if(err)
{
console.log("err: "+err);
}
});
Frustratingly, I'm not getting any errors from mongoose whatsoever, but nothing seems to show up.
There seem to be a lot of questions about no callback with mongoose and mongo.
Here's a couple that I've looked at that I don't think are the problem for me:
Listen for the callback quickly:
Mongoose Connection I
moved my db.on('open'... call to before my connect call in case of a
race condition.
Is Mongo running?
Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
Yes, and on port 27017
Also for reference I'm following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
One thing I am doing that I'm worried about is I've split my code up into multiple files. So this mongoose connection code is being called from a app/models/host.js (or bear.js in tutorial) file. Let me know if posting the other files would be helpful.
I also faced the same issue.
Check that the Mongoose version you are using supports the MongoDb server version
Check compatibility on this link: http://mongoosejs.com/docs/compatibility.html
Change the version of Mongoose in package.json file accordingly.
Hope this helps!
Haven't really solved the problem but I found a work-around... not using mongoose. Would still appreciate connecting to mongoose, especially as I was trying to follow a tutorial.
Here's my code that successfully connects to mongodb:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = "mongodb://localhost:27017/host";
//Go Ahead and connect & sketchily initialize the db
var db;
var collection;
MongoClient.connect(url,function(err,database){
if(err){
console.log("Coudln't connect to mongo. Error"+err);
} else{
db = database;
collection = db.collection('hosts');
console.log("Connected to mongo, db good to go");
}
});

mongoose never stops loading

I am on windows. The local database is running fine, I can write to and find collections with the mongo command line tool. The local nodejs is running fine as well. When I remove my mongoose code, I can reach my endpoints.
When I start the node server with the mongoose code, I get this message:
23:05:57 web.1 | started with pid 20860
23:05:58 web.1 | { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
23:05:58 web.1 | js-bson: Failed to load c++ bson extension, using pure JS version
23:05:58 web.1 | Node app is running at localhost:5000
The server starts, although the error is worrisome (have tried to fix it for a good while, no luck yet), but it doesn't seem like a fatal error.
When I try to access one of my endpoints, either through Postman API, the browser or my application, it tries to connect forever. I can also see in mongo that a connection to the db never is made.
This is the code I have right now:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
mongoose.connection.on("open", function(ref) {
console.log("Connected to mongo server.");
return start_up();
});
mongoose.connection.on("error", function(err) {
console.log("Could not connect to mongo server!");
return console.log(err);
});
mongoose.connect("mongodb://localhost/test");
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
app.get('/', function(request, response) {
response.send("Hello StackOverflow");
});
I've been sitting quite a few hours over the last three days trying to make it work, feels like I've been through every remotely relevant google search at this point. Hope you can help me out. :)
EDIT: If I go with mongoose version 3.8.3. The MODULE_NOT_FOUND error disappears. But it doesn't fix the never ending load.

Unable to connect to mongodb via express project

Tracing the documentation here and failing to load bson apparently. After running npm start I receive:
Snippet:
var mongo = require("mongodb").MongoClient;
//connect to db server
mongo.connect("mongodb://localhost:28017/myDb", function(err, db){
if(!err) {
console.log("Connected to Database")
}
else{
console.log("failed to connect");
}
});
I have tried updating/reinstalling the driver modules as well. Totally new to the framework & db and this type of error feels so trivial that it is discouraging that I am unable to figure it out. Help!
The default port for mongodb is 27017 (and then 28017 is for a web status page).
http://docs.mongodb.org/manual/reference/default-mongodb-port/
Try this connect string:
"mongodb://localhost:27017/myDb"

Resources