mongoose.connection()和mongoose.createConnection()之间的混淆

时间:2012-10-31 16:54:03

标签: node.js mongoose

我已经研究猫鼬三天了,我对使用这两种方法感到困惑(我知道" mongoose.connection()"将被弃用未来......)

问题是:当我试图转换(从" mongoose.connection()"到" mongoose.createConnection()")action.js这个例子https://gist.github.com/2785463的文件似乎对我不起作用......

我的代码......

var mongoose = require('mongoose'),
db = mongoose.createConnection('localhost', 'test');

db.on('error', function () {
  console.log('Error! Database connection failed.');
});

db.once('open', function (argument) {
  console.log('Database connection established!');

  mongoose.connection.db.collectionNames(function (error, names) {
    if (error) {
      console.log('Error: '+ error);
    } else {
      console.log(names);
    };
  });
});

并且我的终端输出(在我的ubuntu终端上键入" node test.js")

Database connection established!

/home/_user_/Scrivania/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:437
    throw err;
          ^
TypeError: Cannot call method 'collectionNames' of undefined
  at NativeConnection.<anonymous> (/home/_user_/Scrivania/test2.js:11:25)
  at NativeConnection.g (events.js:192:14)
  at NativeConnection.EventEmitter.emit (events.js:93:17)
  at open (/home/_user_/Scrivania/node_modules/mongoose/lib/connection.js:408:10)
  at NativeConnection.Connection.onOpen (/home/_user_/Scrivania/node_modules/mongoose/lib/connection.js:415:5)
  at Connection._open (/home/_user_/Scrivania/node_modules/mongoose/lib/connection.js:386:10)
  at NativeConnection.doOpen (/home/_user_/Scrivania/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:47:5)
  at Db.open (/home/_user_/Scrivania/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:287:14)
  at Server.connect.connectCallback (/home/_user_/Scrivania/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:235:7)
  at g (events.js:192:14)

1 个答案:

答案 0 :(得分:4)

如果您不致电mongoose.connect(),则mongoose.connection不包含开放式连接。您应该使用mongo.createConnection()来电中的返回值(已保存到db)。

所以代码的最后一部分应该改为:

<强>已更新

db.db.collectionNames(function (error, names) {
  if (error) {
    console.log('Error: '+ error);
  } else {
    console.log(names);
  };
});

我在collectionNames上看不到Connection方法;看起来你必须按照属性进入本机连接对象才能访问它(参见上面的代码)。