Mongoose never connects to mongodb - node.js

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");
}
});

Related

NodeJS mongoose connections issue

I'm new at NodeJS and today started MongoDb section. I watch NodeJS videos (which recorded in 2016) , they connecting with mongoose. But it is not working correctly on me.
Codes :
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var mongoDB = "mongodb://localhost/nodedb";
mongoose.connect(mongoDB,{ useNewUrlParser: true } ,function(err,err){
if(err){
console.log("Cant connect");
}else{
console.log("Connected to :" + mongoDB);
}
})
With this method I can connect. At least apperaing in Console :
Connected to :mongodb://localhost/nodedb
But there are some errors and one of them is :
Unhandled rejection MongoError: port must be specified
I write mongodb://localhost:27017/nodedb . But now couldn't connect. Where are issue?
You need to specify mongodb port, default one is 27017
https://docs.mongodb.com/manual/reference/default-mongodb-port/
I use mongoose like this:
mongoose.connect('mongodb://localhost:27017/somename')
.then((db)=>{console.log(`connected`);})
.catch(error=>console.log(error));

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

How mongodb connection works on concurrent requests in NodeJS express server?

I am new to mongoDB and I'm currently working on setting it up with Node express server. I wonder how to manage concurrent requests to the mongodb to read the collection data using the mongoose driver module.
For example:
If 100 users are accessing my server at a time (http://xxxxxx.com/showusers), how will the mongodb connection in the express server work? Will it be a single connection or split into 100 connections, one for each request?
How can I close the connection object in mongodb efficiently after the operation? Or can we leave the connection in the express server as in the below code?
Here follows my code..
Server.js
var express = require('express');
var app = express();
app.set('port', config.port);
app.get('/users',storeusersapi.showUsers);
app.get('/storeUser',storeusersapi._insertUserDetails);
app.get('/findUser/:email',storeusersapi._findUser);
app.listen(app.get('port'),function(){
log.info('Express app started on port ' + app.get('port'));
});
storeusersapi.js
var mongoose = require('mongoose');
var log = require('../config/logger');
// Mongoose connection to MongoDB (ted/ted is readonly)
mongoose.connect('mongodb://localhost/mydb', function (error) {
if (error) {
log.error("MongoDB Connection failure - " +error);
}else{
log.info('MongoDB is connected Successfully!!!');
}
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
// Mongoose Model definition
var User = mongoose.model('users', UserSchema);
exports.showUsers = function(req,res){
User.find({}, function (err, docs) {
res.json(docs);
});
};
exports._insertUserDetails = function(req,res){
var object = new User({first_name:'bob',last_name:'sel',email:'sel#xxxxx.com'});
object.save(function (err) {
if (err) {
log.error('Insertion error - '+ err);
}
else {
log.info("User Stored into database!!!");
}
});
};
exports._findUser = function(req,res){
User.find({ email: req.params.email }, function (err, docs) {
res.json(docs);
});
};
I have answered for both of your question separately.
1. How will the mongodb connection in the express server work?
Once a connection is created to the mongodb database.(using mongoose or any other framework) It will create a pool of connections with that. (Mongoose default pool size is 5, 100 in python) The created connection pool is maintained by the driver therefore those connections can be re-used when connections to the database are required.
The best practice is to create a new connection only once for the whole application. Once connection is created the connection object will be used as a singleton. When you connect to the database using mongoose models, separate connections are allocated from the created connection pool.
If you are going to create a new connection each time then It will cause to a connection churn.
2. How can I close the connection object in mongodb efficiently after the operation ?
I am not sure 100% about this answer. My suggestion is to disconnect the connection when the express application exits.
var db = mongoose.connect('mongodb://localhost:27017/database');
db.disconnect();
According to my knowledge what you have don in the code is correct. You have created a new connection only once. Since the connection pool is created with that you don't need to create more connections.
Please go through this link to get a clear understanding on connection pools and their usage.
https://dzone.com/articles/deep-dive-connection-pooling

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"

Mongoskin Connection Fails (Error: connection closed)

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".

Resources