node.js中用typescript连接mongodb数据并设置断开后自动重启连接


发布者 ourjs  发布时间 1670985574362
关键字 mongodb  Node.JS  TypeScript 

 

Node.js与mongodb可以只创建一条连接以提高性能,如果出现数据连接断开,可以通过侦听“serverHeartbeatFailed”,自动重连,示例代码如下:

 

import { Db, MongoClient } from 'mongodb'

let client: MongoClient
let database: Db

export const init = async(interval = 2000) => {
client = new MongoClient('mongodb://localhost/tst')

try {
await client.connect()
database = client.db()

client.once('serverHeartbeatFailed', (e) => {
console.log('Database connect error will reconnect again')
setTimeout(init, interval)
})
console.log('Database connected')
} catch(e) {
console.log('Database init err will reconnect again')
setTimeout(init, interval)
}
}