Mongoose连接然后立即断开连接(Node.js + Express)

时间:2015-11-10 15:55:15

标签: javascript node.js mongodb express mongoose

我有一个使用Mongoose连接到MongoDB的Express(Node.js)应用程序。 在过去几周它一直很好,但在最近几天它一直让我发疯。

服务器似乎连接到MongoDB然后立即断开连接。 来自global日志:

2015-11-10T15:47:02.083+0000 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:33994 #178 (2 connections now open)
2015-11-10T15:47:02.084+0000 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:33995 #179 (3 connections now open)
2015-11-10T15:47:02.084+0000 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:33996 #180 (4 connections now open)
2015-11-10T15:47:02.085+0000 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:33997 #181 (5 connections now open)
2015-11-10T15:47:02.085+0000 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:33998 #182 (6 connections now open)
2015-11-10T15:47:02.465+0000 I ACCESS   [conn178] Successfully authenticated as principal server on MY_DB_NAME
2015-11-10T15:47:02.466+0000 I ACCESS   [conn179] Successfully authenticated as principal server on MY_DB_NAME
2015-11-10T15:47:02.466+0000 I ACCESS   [conn180] Successfully authenticated as principal server on MY_DB_NAME
2015-11-10T15:47:02.466+0000 I ACCESS   [conn181] Successfully authenticated as principal server on MY_DB_NAME
2015-11-10T15:47:02.466+0000 I ACCESS   [conn182] Successfully authenticated as principal server on MY_DB_NAME
2015-11-10T15:47:02.475+0000 I NETWORK  [conn178] end connection 127.0.0.1:33994 (5 connections now open)
2015-11-10T15:47:02.475+0000 I NETWORK  [conn179] end connection 127.0.0.1:33995 (4 connections now open)
2015-11-10T15:47:02.475+0000 I NETWORK  [conn180] end connection 127.0.0.1:33996 (3 connections now open)
2015-11-10T15:47:02.475+0000 I NETWORK  [conn181] end connection 127.0.0.1:33997 (2 connections now open)
2015-11-10T15:47:02.475+0000 I NETWORK  [conn182] end connection 127.0.0.1:33998 (1 connection now open)

你可以从同一秒钟看到它。

我如何联系:

var mongoose = require('mongoose');
mongoose.connect('mongodb://MY_USERNAME:MY_PASSWORD@127.0.0.1:27017/MY_DB_NAME');
mongoose.connection.on('open', function (ref) {
  console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function(err) {
  console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?');
  console.log(err);
});

服务器记录Connected to mongo server.。 这可能来自哪里?

我做了一个全新的安装,它是一样的,所以我想它一定是我的代码。 我应该粘贴其他任何代码吗?

感谢任何帮助。

根据詹姆森的建议,我将mongoose.connect更改为var appCon = mongoose.createConnection(url)。检查日志,实际上似乎确实使连接粘住。怪异。

.connect显然不是此问题的根源。我没有足够的信息。

如何检查“引擎盖下”?

好吧..这很尴尬。我实际上在一个文件的底部留下了一个mongoose.connection.close();,当我希望连接是动态的时候,只在我需要时才打开。

这实际上需要3天才能找到。真是浪费时间!

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

var appConnection = mongoose.createConnection('mongodb://127.0.0.1:27017/bookAPI');

appConnection.on('error', console.error.bind(console, 'connection error:'));
appConnection.once('open', function callback () {
    console.log("h");
});