Error: Trying to open unclosed connection.

时间:2022-01-29 15:46:26

错误:试图打开未关闭的连接。在我自己写model文件的时候,重复打开了连接数据库的操作,所以报这种错误。

错误实例:

两个model文件:

userModel.js

var mongoose = require('mongoose');
var config = require('./../config/config');
mongoose.connect(config.mongodb);
var PostSchema = new mongoose.Schema({
    title:String,//标题
    author:String,//作者
    article:String,//文章内容
    publishTime:String,//发表时间
    postImg:String,//封面
    comments:[{
        name:String,
        time:String,
        content:String
    }],//评论
    pv:Number//访问次数
});
module.exports = mongoose.model('Post',PostSchema ); 

userModel.js

var mongoose = require('mongoose');
var config = require('../cofig/config');//引用同级目录下的文件
mongoose.connect(config.mongodb);
var UserSchema = new mongoose.Schema({
    username:String,
    password:String,
    email:String
});

module.exports = mongoose.model('User', UserSchema);
 

我们应该在我们运行我们的项目的时候打开数据库的连接,之后再每个model文件直接访问就可以,不要每一次都要进行连接。修正后的代码:

在我们项目的app.js或index.js(就是所谓的启动文件)增加共有的数据库连接

var mongoose = require('mongoose');
var dbName = 'blog'; //数据库的名称
var url = 'mongodb://localhost/'+dbName; 
var mongoOptions = {
    server: {
        socketOptions: {
            keepAlive: 1
        }
    }
};
mongoose.connect(url, mongoOptions);
mongoose.connection.on('error', function (err) {
    console.log('Mongo Error:' + err);
}).on('open', function () {
    console.log('Connection opened');
});

之后再每个model进行引用:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
    username:String,
    password:String,
    email:String
});

module.exports = mongoose.model('User', UserSchema);