为什么会出现“尝试打开未关闭的连接"错误? [英] Why am I getting error "Trying to open unclosed connection."?

查看:69
本文介绍了为什么会出现“尝试打开未关闭的连接"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过mongoose将节点应用程序连接到mongodb.我可以添加文档,但似乎可行,但是出现错误{ [Error: Trying to open unclosed connection.] state: 2 }.

I am trying to connect my node app to mongodb via mongoose. It seems to be working, as I can add documents, but I get the error { [Error: Trying to open unclosed connection.] state: 2 }.

我创建了一个非常简单的应用程序,目的是确保在连接实际应用程序之前一切正常.

I created a very simple app, just to make sure everything is working properly before connecting my actual app.

这是我简单的应用程序:

Here is my simple app:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var timeSchema = new Schema({ timestamp: String });
var Time = mongoose.model('Time', timeSchema);

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

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function () {

  var testA = new Test({ timestamp: Date() });

});

我还尝试将db.close()添加到末尾,但这没什么区别.

I also tried adding db.close() to the end, but it made no difference.

它在具有以下功能的Ubuntu 14.04 VPS上运行:

This is running on a Ubuntu 14.04 VPS with:

  • Node.js v0.10.3
  • MongoDB 2.6.3
  • 猫鼬1.4.21

推荐答案

在我看来,您正在尝试创建另一个连接而不关闭当前连接.因此,您可能要使用:

In my opinion, you are trying to create another connection without closing the current one. So, you might want to use:

createConnection()代替connect().

在您的情况下,它看起来像这样:

In your case, it would look like this:

db = mongoose.createConnection('mongodb://localhost/mydb');

这篇关于为什么会出现“尝试打开未关闭的连接"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆