mongoose 连接问题
发布于 4 个月前 作者 ray1888 872 次浏览 来自 问答
function connect_mongo(db){
    console.log('HOSt',MONGO_HOST)
    if( MONGO_USER != '' && MONGO_PASSWORD != ''){
        var dburl = 'mongodb://'+ MONGO_USER + ":" + MONGO_PASSWORD +'@'+ MONGO_HOST+":"+MONGO_PORT+'/'+db
    } else {
        var dburl = 'mongodb://'+ MONGO_HOST +':'+MONGO_PORT+'/'+ db
    }
    console.log('dburl',dburl)
     dbConnection = mongoose.createConnection(
        dburl,{
            config: {
                autoIndex: false //不自动创建索引
            },
            server: {
                auto_reconnect: true //自动重连
            }
        }
    )

    dbConnection.on('open',()=>{
        console.log(db+'连接成功')
    })  

    dbConnection.on('error',()=>{
        console.log(db+'连接失败')
    })

    dbConnection.on('close',()=>{
        console.log(db+'连接关闭')
    })

    return dbConnection;
}

使用一个函数去进行数据的连接,但是为什么我明明填下去的mongodbhost是192.168.0.253,log打出来也是

// This is log
2018-01-04 20:20 +08:00: HOSt 192.168.0.253
2018-01-04 20:20 +08:00: dburl mongodb://192.168.0.253:27017/argus-web
2018-01-04 20:20 +08:00: HOSt 192.168.0.253
2018-01-04 20:20 +08:00: dburl mongodb://192.168.0.253:27017/argus-statistics
2018-01-04 20:20 +08:00: HOSt 192.168.0.253
2018-01-04 20:20 +08:00: dburl mongodb://192.168.0.253:27017/argus-alert
2018-01-04 20:20 +08:00: HOSt 192.168.0.253
2018-01-04 20:20 +08:00: dburl mongodb://192.168.0.253:27017/argus-users
2018-01-04 20:20 +08:00: argus-statistics连接成功
2018-01-04 20:20 +08:00: argus-web连接成功
2018-01-04 20:20 +08:00: argus-alert连接成功
2018-01-04 20:20 +08:00: argus-users连接成功

但是之后就会报连接错误,错误的是地址错了

MongoError: failed to connect to server [2.168.0.253:27017] on first connect [MongoError: connect ETIMEDOUT 2.168.0.253:27017]
    at Pool.<anonymous> (F:\git\argus-web\server\node_modules\mongodb-core\lib\topologies\server.js:336:35)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (F:\git\argus-web\server\node_modules\mongodb-core\lib\connection\pool.js:280:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (F:\git\argus-web\server\node_modules\mongodb-core\lib\connection\connection.js:187:49)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)

有大神们知道是什么原因吗?

4 回复

但是使用localhost的时候就不会报错

是不是服务端那个数据库连接池用满了之类的 猜测 等大神解惑

有大神能解释一下吗?我连填localhost 最后链接报错的时候,localhost也变成了calhost,跟上面127.0.0.1一样,没了前两个字符,变成7.0.0.1

这里的 connect 函数有连续执行么,像是执行多次导致产生的错误

回到顶部