【Mongoose|MongoDB】MongoNotConnectedError: Client must be connected before running operations

文章讲述了在Node.js中使用Mongoose操作MongoDB时遇到的MongoNotConnectedError报错,强调了在异步操作前后连接和关闭数据库的重要性。正确的方法是在async/await或then块中处理数据库操作,避免因数据库未连接导致的错误。
摘要由CSDN通过智能技术生成

报错图

在这里插入图片描述

报错代码

- 百度翻译 : 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}已离线,关闭数据库`);
        }
    })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值