xbd
xbd

Reputation: 975

Mongoose and Mongo error, mongoose.connection.host returns null

So I been debugging this weird error in which saving and findone does not work, overtime I suspect the connection is not right so I did a print out

console.log(mongoose.connection.host);
console.log(mongoose.connection.port);

In which both returns null

This is especially confusing when

var mongoose = require('mongoose'),
    connStr = 'mongodb://localhost:27017/task_test2';

mongoose.createConnection(connStr, function(err){
    if (err) throw err;
    console.log ('Successfully connected to MongoDB');
    console.log(mongoose.connection.host);
    console.log(mongoose.connection.port);
});

There are no errors throwed?

Why is this happening, and how would I fix it?

Thanks

Upvotes: 0

Views: 1383

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You should be using mongoose.connect instead of mongoose.createConnection.

You'd only want to use createConnection if you need more control than you get with the default connection pool provided by connect.

So do this instead:

mongoose.connect(connStr, function(err){
    if (err) throw err;
    console.log ('Successfully connected to MongoDB');
    console.log(mongoose.connection.host);
    console.log(mongoose.connection.port);
});

mongoose.connection is the default connection which is why your code was returning null for its properties.

Upvotes: 1

Related Questions