mongoose Topology was destroyed 处理

版权声明:转载请评论留言 https://blog.csdn.net/solocao/article/details/83351338

在用 node 的 mongoose 模块操作 mongodb 数据库的时候,本来正常返回数据,但是有时候会返回空白页,控制台里报错:

Topology was destroyed

数据库连接代码如下:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;

网上百度下,没什么合适的解释,大概理解一个意思,就是长时间没有请求,数据库断开了。
我又去找了 mongoose 重连数据库的方法,比较合理的是设置一个连接池,并自动重新连接,方法如下:

先定义一个 options 对象,如下:

var options = {  
    server: {
        auto_reconnect: true,
        poolSize: 10
    }
};
  • poolSize是连接池最多可连接的数量,
  • auto_reconnect是自动重新连接,设置为 true, 然后在连接数据库的时候将 options 对象当作参数传入:
mongoose.connect('mongodb://localhost/test',options);

猜你喜欢

转载自blog.csdn.net/solocao/article/details/83351338