报错图
报错代码
- 百度翻译 : MongoNotConnectedError:运行操作之前必须连接客户端
import mongoose from "mongoose";
const { connection, connect } = mongoose
// .....很多代码
// .....很多代码
// .....很多代码
// .....很多代码
// .....很多代码
/**
* 连接数据库
* @param {Number} roles 角色,默认:0 ,用户只读角色 | 0 用户只读角色 | 1 用户读写角色 | 2 超级角色
*/
const conn = (roles = 0) => connect(rolesArr[roles]).catch(err => false)
/**
* 关闭连接
*/
const closeConn = () => connection.close()
export {
closeConn,
conn
}
原因
- 数据库没有完成连接、关闭后操作数据库
- 数据库是异步的,一定要在then或async\await后操作数据库
解决
- 在anync\await\then后再对数据库进行操作
码参考
/**
* 连接数据库
* @param {Number} roles 角色,默认:0 ,用户只读角色 | 0 用户只读角色 | 1 用户读写角色 | 2 超级角色
*/
const conn = async (roles = 0) => await connect(rolesArr[roles]).catch(err => false)
/**
* 关闭连接
*/
const closeConn = async () => await connection.close()
总结
- 操作数据库前无论什么场合,一定一定要在await\asny、then之后操作,不能粗心大意
- await、then虽然会对响应速度有一定延迟,但一定要await\asny、then之后操作数据库
错误代码
req.on('close', () => {
if (findUser) {
findUser.online = 0
findUser.save()
closeConn()//关闭数据库连接
console.log(`用户${em}已离线,关闭数据库`);
}
})
正确代码
req.on('close', async () => {
if (findUser) {
findUser.online = 0
await findUser.save()
await closeConn()//关闭数据库连接
console.log(`用户${em}已离线,关闭数据库`);
}
})