[ Node.js failing to connect to MongoDB ]
I am new to both Node.js and MongoDB. I am following this guide: http://howtonode.org/express-mongodb to create a simple blog with Node.js and MongoDB.
When node tries to connect to MongoDB, it is failing and I have no idea why.
In my app.js file i have:
var articleProvider = new ArticleProvider('127.0.0.1', 27107);
In my articleprovider-mongodb.js file I have
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
ArticleProvider = function(host, port) {
this.db = new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(err){
if(err) {
console.log(err);
}
});
};
In my terminal I get:
9 Aug 10:48:19 - [nodemon] starting node app.js
[Error: failed to connect to [127.0.0.1:27107]]
I am running node.js v0.8.6 and mongodb v2.0.6
I have other code in these files but from what I can see it shouldn't effect the db connection.
Answer 1
That happens when the mongod process is not running or you're connecting to the wrong host/ip.
Do you have it running on your localhost and if so can you access it from your from the mongo shell?
Try to test it with a minimum version of an app with node, express and the mongodb nodejs driver.
I tested it with these files:
- http://howtonode.org/express-mongodb/articleprovider-mongodb.js
- http://howtonode.org/express-mongodb/app.js
And it worked fine, except for the last two lines of app.js, because of express 3.x instead of 2.x used in the example.
var server = app.listen(3000);
console.log("Express server listening on port %d in %s mode", server.address().port, app.settings.env);