Mongoose和Mongo错误,mongoose.connection.host返回null

时间:2014-04-19 22:12:18

标签: node.js mongodb mongoose

所以我一直在调试这个奇怪的错误,其中save和findone不起作用,加班我怀疑连接不对,所以我打印了

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

其中两者都返回null

时尤其令人困惑
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);
});

没有错误抛出?

为什么会发生这种情况,我该如何解决?

由于

1 个答案:

答案 0 :(得分:1)

您应该使用mongoose.connect代替mongoose.createConnection

如果您需要的控制力超过createConnection提供的默认连接池,则您只想使用connect

所以这样做:

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是默认连接,这就是您的代码为其属性返回null的原因。