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;
}
}
});
Related
Hey guys so I'm pretty new to creating modules, I'm having a bit of trouble accessing my mongodb connection pool from my main application.
Here's the module:
// mongo-pool.js
// -------------
var assert = require('assert');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'connection_url';
var mongoPool = {
start: function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Successfully connected to mongo");
// Make the db object accessible here?
});
}
}
module.exports = mongoPool;
When I require mongo-pool.js and call mongoPool.start() It says it successfully connected to mongo, although the db object is not accessible to make queries. Here is the main js file:
var mongoPool = require('./mongo-pool.js');
var pool = mongoPool.start();
var collection = pool.db.collection('accounts');
collection.update(
{ _id: 'DiyNaiis' },
{ $push: { children: 'JULIAN' } }
)
The variable pool is undefined. I can't seem to figure out why, I've tried return db in the module, didn't seem to work.
Any help is appreciated, thank you!
A buddy of mine helped me figure out what the problem was, here's the solution incase anyone runs into it.
I updated my mongo-pool.js module and assigned the db property to itself:
var assert = require('assert');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'my_database_url';
var mongoPool = {
start: function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var self = this;
self.db = db;
// THESE ASSIGNMENTS
console.log("Successfully connected to mongo");
// Make the db object accessible here?
});
}
}
module.exports = mongoPool;
Then in my main.js file:
var mongoPool = require('./mongo-pool.js');
// Include My mongo global module
new mongoPool.start();
// Initialize the new MongoDB object globally
setTimeout(function() {
console.log(db);
}, 3000);
// Set a 3 second timeout before testing the db object...
// It will return undefined if it's called before the mongo connection is made
Now the db object is globally available from a module.
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.
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'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 am starting to use appfog services in order to host node application.
I am getting trouble trying to use mongodb in my application.
In you tutorial here: https://docs.appfog.com/services/mongodb#walkthrough it is written to connect mongodb like this:
require('mongodb').connect(mongourl, ...
while mogourl is the url generated by the generate_mongo_url function.
The problem is that I am using newer api (I think) and I cannot pass url to the open method. This is how I am using mongodb:
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) { ...
Where and how can I use the generated mongourl? How can I pass the credentials and the mongo variable used in generate_mongo_url function?
UPDATE
According to #mjhm suggestion, this is my open function:
var mongoService = null;
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
mongoService = env["mongodb-1.8"][0]["credentials"];
} else {
mongoService = {
"hostname": "localhost",
"port": 27017,
"isLocal": true,
"username": "",
"password": "",
"name": ""
};
}
this.mongoClient.open(function(err, mongoClient) {
if (!err) {
console.log("Open DB Success");
var db = mongoClient.db(DB_NAME);
if (!mongoService.isLocal) {
db.authenticate(mongoService.username,
mongoService.password, function (err, result) {
if (!err) {
console.log("Authenticate DB Success");
doAction();
} else {
console.log("Authenticate DB Error: " + err);
}
});
} else {
doAction();
}
} else {
console.log("Open DB Error: " + err);
}
});
When I am running this code on appfog, I am waiting a lot of time (more then 20 seconds) and then I get:
$ curl myappname.eu01.aws.af.cm/list
curl: (52) Empty reply from server
Any idea what is wrong?
What you are looking for is the MongoClient.connect function
http://mongodb.github.com/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect
It takes the url you are talking about.
the URL where your client / driver wants to connect to was 'localhost'. I replaced it with a
variable mongoUrl
var mongoClient = new MongoClient(new Server(mongoUrl, 27017));
You need to authenticate after opening the database. The way to think of it is that authentication happens against the database not the connection, so as you discovered the generate_mongo_url function isn't very useful.
For example:
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db = mongoClient.db('test');
db.authenticate('me', 'mypwd', function (err, result) {
var coll = db.collection('query_example3');
coll.find().toArray(function(err, result) {
console.log(result);
process.exit(0);
});
});
});