Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to connect to mongoDB using mongoose

I'm following this book addyosmani - backbone-fundamentals for creating a simple backbone.js app with node server and mongodb as backend.

As instructed, I've installed the latest versions of Node.js fromnodejs.org and mongodb from www.mongodb.org and ran mongodb by followed the instructions.


The package.json is as follows:

    {
    "name": "backbone-library",
    "version": "0.0.1",
    "description": "A simple library application using Backbone",
    "dependencies": {
        "express": "~3.1.0",
        "path": "~0.4.9",
        "mongoose": "~3.5.5",
        "body-parser": "~1.9.1"
    }
}

The tutorial then suggests to add the following to server.js file for connection to mongoDB:

//Connect to database
mongoose.connect( 'mongodb://localhost/library_database' );

//Schemas
var Book = new mongoose.Schema({
    title: String,
    author: String,
    releaseDate: Date
});

//Models
var BookModel = mongoose.model( 'Book', Book );

I've got confused with the following line:

mongoose.connect( 'mongodb://localhost/library_database' );

because the book doesn't mention anything regarding creating a database named library_database and I haven't created manually - Still if I run the following in server.js:

mongoose.createConnection( 'mongodb://localhost/library_database' );

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
// we wait till mongo is ready before letting the http handler query users:
db.once('open', function () {
    console.log('Running');
    //Schemas
    var Book = new mongoose.Schema({
        title: String,
        author: String,
        releaseDate: Date
    });

    //Models
    var BookModel = mongoose.model('Book', Book);
});

It logs Running..! (how come because I didn't create any library_database..?)

But, If I further follow the book by adding a GET request handler as shown below:

    //Get a list of all books
app.get( '/api/books', function( request, response ) {
    return BookModel.find( function( err, books ) {
        if( !err ) {
            return response.send( books );
        } else {
            return console.log( err );
        }
    });
});

and hit it with the following request:

jQuery.get( '/api/books/', function( data, textStatus, jqXHR ) {
  console.log( 'Get response:' );
  console.dir( data );
  console.log( textStatus );
  console.dir( jqXHR );
});

According to the tutorial I'm supposed to see the logs, Instead I get the following error:

GET http://localhost:4711/api/books/ net::ERR_EMPTY_RESPONSE

The DB is currently listening to default port with the default database "test".

I tried use library_database in mongo shell, but still get the same response from the node server.

Do I need to manually create a db for the application..? If so, how can I create an instance for the app and connect to it from node server..?

Or does mongoose automatically creates such a db in the applications root folder (very unlikely to happen)..?

I'm pretty new to node.js, mongodb, mongoose etc so I might be missing some basic concepts. What am I missing..?

like image 923
T J Avatar asked Nov 30 '14 11:11

T J


People also ask

Why is my MongoDB not connecting?

Your connection from client to server is blocked by firewall or network configuration. A MongoDB server is not listening on the requested Host/IP and port (check they are both correct)

How do we connect mongoose to our MongoDB database?

You can connect to MongoDB with the mongoose.connect() method. mongoose.connect('mongodb://localhost:27017/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, try using 127.0.0.1 instead of localhost .

Can I use mongoose with MongoDB?

Mongoose is an ODM (Object Data Modeling) library for MongoDB. While you don't need to use an Object Data Modeling (ODM) or Object Relational Mapping (ORM) tool to have a great experience with MongoDB, some developers prefer them.

How MongoDB works with mongoose?

Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A "collection" of "documents" in a MongoDB database is analogous to a "table" of "rows" in a relational database.


3 Answers

I just found the examples for connect and createConnection in the docs:

mongoose.connect('mongodb://user:pass@localhost:port/database');
//-----------------------------------------------^

The one in tutorial is as follows:

mongoose.connect( 'mongodb://localhost/library_database' );

It is missing the port number. I changed it by adding default port number as follows:

mongoose.createConnection('mongodb://localhost:27017/library_database');

and now I'm getting the response!

like image 94
T J Avatar answered Oct 09 '22 18:10

T J


You might find this helpful from mongoose documentation

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

var conn = mongoose.createConnection('your connection string') , MyModel = conn.model('ModelName', schema) , m = new MyModel; m.save(); // works vs

var conn = mongoose.createConnection('your connection string') , MyModel = mongoose.model('ModelName', schema) , m = new MyModel; m.save(); // does not work b/c the default connection object was never connected

like image 3
Merhawi Fissehaye Avatar answered Oct 09 '22 19:10

Merhawi Fissehaye


This is how I have connected.

var mongoose = require('mongoose/');
var db = mongoose.connect('mongodb://localhost/newdbcoll');


//e.g. mongodb://username:server@mongoserver:10059/somecollection
//mongoose_auth: 'mongodb://admin:[email protected]:27017/chrome-server'

And I am able to connect.

like image 1
Varun Chakervarti Avatar answered Oct 09 '22 19:10

Varun Chakervarti