[英]Why am I getting error “Trying to open unclosed connection.”?
I am trying to connect my node app to mongodb via mongoose. 我正在尝试通过mongoose将我的节点应用程序连接到mongodb。 It seems to be working, as I can add documents, but I get the error { [Error: Trying to open unclosed connection.] state: 2 }
. 它似乎正在工作,因为我可以添加文档,但我收到错误{ [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() });
});
I also tried adding db.close()
to the end, but it made no difference. 我也尝试将db.close()
添加到最后,但没有区别。
This is running on a Ubuntu 14.04 VPS with: 这是在Ubuntu 14.04 VPS上运行的:
In my opinion, you are trying to create another connection without closing the current one. 在我看来,你试图创建另一个连接而不关闭当前的连接。 So, you might want to use: 所以,您可能想要使用:
createConnection() instead of connect()
. createConnection()而不是connect()
。
In your case, it would look like this: 在你的情况下,它看起来像这样:
db = mongoose.createConnection('mongodb://localhost/mydb');
I had the same issue and found that I had the below connection in another file, which was the reason why I couldn't connect with a different database name. 我有同样的问题,发现我在另一个文件中有以下连接,这就是为什么我无法连接不同的数据库名称。 The below createConnection
is needed: 需要以下createConnection
:
db = mongoose.createConnection('mongodb://localhost/mydb');
What I had in another file: 我在另一个文件中有什么:
db = mongoose.Connection('mongodb://localhost/mydb');
just use mongoose.connect('...');
只需使用mongoose.connect('...');
once . 一次 。
maybe in your root app.js or index.js file, not in every model or database related files if your are importing (including) them. 可能在您的根app.js或index.js文件中,如果您正在导入(包括)它们,则不在每个模型或数据库相关文件中。
Anyways, if you still have doubt you can check it by: 无论如何,如果您仍有疑问,可以通过以下方式检查:
var mongoose = require('mongoose');
var db = mongoose.connection;
db.once('connected', function() {
console.log('mongoDB is connected');
});
shouldn't your 不应该你的
db.once('open', function () {
var testA = new Test({ timestamp: Date() });
});
be 是
db.once('open', function () {
var testA = new Time({ timestamp: Date() });
});
If "Test" is a different schema based on a different connection, that might affect i think 如果“测试”是基于不同连接的不同模式,那可能会影响我认为
I had the same issue, but it was due to a typo: 我有同样的问题,但这是由于一个错字:
express-sessions
instead of express-session
express-sessions
而不是express-session
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.