The following is the connection string and options i'm using from node.js to connect to mongodb. My web application keeps re-trying and never posts back if the mongodb server is down. Where do I set the connection timeout so I can say db server is down when it is? (The following code works perfectly when the mongo server is up).
(function(database) {
var mongodb = require("mongodb");
database.ObjectID = mongodb.ObjectID;
var mongoUrl = "mongodb://localhost:27017/mydb";
var dbconn = null;
database.getDBConn = function(next){
if(dbconn){ next(null, dbconn); return; } //already connected: return dbconn
mongodb.MongoClient.connect(mongoUrl,
{server: {socketOptions: {connectTimeoutMS: 500}}}, function(err, database){
if(err){ next(err, null); return; } //connection fail: return error
dbconn = {db: database,
movies: database.collection("movie") };
next(null, dbconn); //connection success: return dbconn
});
}
})(module.exports);
Looking at http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html I would say use
MongoClient.prototype.close
method to check if the connection is closed.If the connection is closed then emit a notification that the database server is down.
Related
I've encountered a bizarre error trying to connect to a MongoHQ MongoDB on Heroku using NodeJS. It worked before and now it has stopped to work. I can connect to database on my local machine, so I guess that MongoHQ is working just fine. On Heroku, the following minimal example throws "Error: failed to connect to [mongodb://xyz.mongohq.com]". Any idea what's wrong?
var Fiber = require('fibers');
var MongoSync = require("mongo-sync");
Fiber(function() {
try {
var server = new MongoSync.Server("mongodb://xyz.mongohq.com:12345");
var db = server.db("app12345678");
db.auth("heroku", "password");
var collection = db.getCollection("my_collection");
console.log(collection.count());
} catch (e) {
console.log(e);
}
process.exit(0);
}).run();
Try specifying the database name and auth credentials all in the connection string.
mongodb://heroku:password#xyz.mongohq.com:12345/app12345678
You could also try connecting using MongoClient and connect as outlined in the driver readme doc.
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
MongoClient.connect(' mongodb://heroku:password#xyz.mongohq.com:12345/app12345678', function(err, db) {
if(err) throw err;
var collection = db.collection('my_collection');
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
console.log(format("count = %s", count));
});
});
});
If that still doesn't work double check everything--recreate the user you want to connect with and then copy the connection string from MongoHQ's admin page replacing the username and password you just created.
I am trying to figure out the best way to pass a mysql connection (using node-mysql) between my routes for express.js. I am dynamically adding each route (using a for each file loop in routes), meaning I can't just pass in the connection to routes that need it. I either need to pass it to every route or none at all. I didn't like the idea of passing it to ones that dont need it so I created a dbConnection.js that the routes can individually import if they need. The problem is that I dont think I am doing it correctly. As of now, my dbConnection.js contains:
var mysql = require('mysql');
var db = null;
module.exports = function () {
if(!db) {
db = mysql.createConnection({
socketPath: '/tmp/mysql.sock',
user: '*********',
password: '*********',
database: '**********'
});
}
return db;
};
And I am importing it into each route using:
var db = require('../dbConnection.js');
var connection = new db();
But I would like to do it like this:
var connection = require('../dbConnection.js');
When I try it like this, however, I get an error saying connection has no method 'query' when I try to make a query.
I find it more reliable to use node-mysql's pool object. Here's how I set mine up. I use environment variable for database information. Keeps it out of the repo.
database.js
var mysql = require('mysql');
var pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASS,
database: process.env.MYSQL_DB,
connectionLimit: 10,
supportBigNumbers: true
});
// Get records from a city
exports.getRecords = function(city, callback) {
var sql = "SELECT name FROM users WHERE city=?";
// get a connection from the pool
pool.getConnection(function(err, connection) {
if(err) { console.log(err); callback(true); return; }
// make the query
connection.query(sql, [city], function(err, results) {
connection.release();
if(err) { console.log(err); callback(true); return; }
callback(false, results);
});
});
};
Route
var db = require('../database');
exports.GET = function(req, res) {
db.getRecords("San Francisco", function(err, results) {
if(err) { res.send(500,"Server Error"); return;
// Respond with results as JSON
res.send(results);
});
};
your solution will work if use db() instead of new db(), which returns an object and not the db connection
var db = require('../dbConnection.js');
//var connection = new db();
var connection = db();
I'm using native mongo driver in Joyent cloud, the node.js application runs fine locally but in Joyent when I run with the username/password that they provided it fails to connect.
This is the code I use to connect:
var db = new MongoDB(dbName, new Server('localhost', 27017 , {auto_reconnect: true}), {w: 1});
db.open(function(e, db){
if (e) {
console.log(e);
} else{
console.log('connected to database :: ' + dbName);
//db.admin().authenticate('admin', '+(uihghjk', function(de , db){
// if(e){
// console.log("could not authenticate");
// }else {
//console.log('connected to database :: ' + dbName);
// }
// });
}
});
What's stopping me from connecting successfully?
Easier if you just use MongoClient
MongoClient.connect('mongodb://admin:password#localhost:27017/db', function (err, db) {
the working code would be like this
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>#cluster0-saugt.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
// creating collection
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Standard URI connection scheme is:
mongodb://[username:password#]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
For Example:
mongodb://admin:pass#abc.com/
Reference: https://docs.mongodb.com/manual/reference/connection-string/
Use <username> : <password> right after // in the URL.
I am using Mongoose to connect and my username and password is admin admin
mongodb+srv://admin:admin#cluster0.c1xrp
This worked for me.
I'm a big Node.js and Mongo newbie, so please be gentle.
So here's my Node.js app:
var mongo = require('mongodb');
var Server = mongo.Server;
var Db = mongo.Db;
var server = new Server('hostname.mongolab.com', 666, {auto_reconnect : true}, {w:0, native_parser: false});
var db = new Db('dbName', server, {safe:true});
db.open(function(err, client) {
if(err) { return console.dir(err); }
client.authenticate('mongolabUser', 'mongolabUserPassword', function(authErr, success) {
if(authErr) { return console.dir(authErr); }
var stream = client.collection('myCollection').find({}).stream();
stream.on('data', function(item) {console.log("Do something with item"); });
stream.on('end', function() {console.log("Empty!");});
});
db.close();
});
Through prodigious use of debugger statements, I've come to the conclusion that the client.authenticate doesn't seem to be run. It looks like it's about to execute that line, but then just leapfrogs over it and goes straight to db.close().
But that's just the first of my problems. At some point prior, I was able to connect in to the database and authenticate, but my user was no retrieving anything in the find({}) command. I tried all sorts of ways, and streams are my latest attempt before deciding to give up on it for now.
Mongolab seems to be on v2.0.7, my mongo installation is v2.2.1. When I use the command line tool to log in as mongolabUser and execute a command like db.myCollection.find(), I get everything in my collection, so it can't be an issue with permissions.
Any advice/suggestions?
client.authenticate() is asynchronous, so the line that calls it starts the authentication, but doesn't wait for the server to respond before moving on to executing the next line, db.close(). So by the time the server responds the connection has been closed by the client.
Does moving the db.close() inside the event handler for stream.end help?
var mongo = require('mongodb');
var Server = mongo.Server;
var Db = mongo.Db;
var server = new Server('hostname.mongolab.com', 666, {auto_reconnect : true}, {w:0, native_parser: false});
var db = new Db('dbName', server, {safe:true});
db.open(function(err, client) {
if(err) { return console.dir(err); }
client.authenticate('mongolabUser', 'mongolabUserPassword', function(authErr, success) {
if(authErr) { return console.dir(authErr); }
var stream = client.collection('myCollection').find({}).stream();
stream.on('data', function(item) {console.log("Do something with item"); });
stream.on('end', function() {
console.log("Empty!");
db.close();
});
});
});
I'm trying to connect an app I have built to a MongoHQ Database.
This is the code:
mongo = require('mongodb')
Server = mongo.Server
Db = mongo.Db
BSON = mongo.BSONPure;
con = null;
server = new Server('staff.mongohq.com', 'THE_PORT', {auto_reconnect: true});
DBCon = new Db('THE_DB', server, {safe: false});
DBCon.authenticate('test_user', 'test_pass', function() {});
DBCon.open(function(err, db) { if(!err) { con = db; } });
I have the database and the user created in MongoHQ. When I connect from the command line, everything works perfectly.
But when I run my app, I get this error:
return this.connectionPool.getAllConnections();
TypeError: Cannot call method 'getAllConnections' of undefined
It fails to connect to the database.
But when I connect to my local database without authentication, it works properly.
So what is the error and how should I fix it?
Thanks! :D
Your authentication call is being sent before the connection has been established. You need to nest the authenticate call within the "open" callback, something like this should work:
mongo = require('mongodb')
Server = mongo.Server
Db = mongo.Db
BSON = mongo.BSONPure;
con = null;
server = new Server('staff.mongohq.com', 'THE_PORT', {auto_reconnect: true});
DBCon = new Db('THE_DB', server, {safe: false});
DBCon.open(function(err, db) {
if(!err) {
db.authenticate('test_user', 'test_pass', function(err){
if(!err) con = db;
}
}
});