无法从MongoDB获取数据及this.DB.close()不是函数问题求助
MongoDB模块问题排查与修复方案
问题1:无法获取有效数据,返回{"_events": {}, "_eventsCount": 0}
原因
find()方法返回的是MongoDB游标(Cursor)对象,并非直接的查询结果数组,直接返回游标会导致输出仅包含游标事件属性conn()方法中this.CLIENT.connect()是异步操作,但conn()未用async/await处理,可能出现数据库操作先于连接完成执行的情况
修复方式
- 将
conn()改为异步方法,在数据库操作前等待连接完成 - 在
getData()中调用toArray()将游标转换为实际数据数组
问题2:报错this.DB.close()不是函数
原因
this.DB是Collection实例,MongoDB的Collection对象没有close()方法,关闭数据库连接需调用MongoClient实例的close()方法
修复方式
将this.DB.close()替换为this.CLIENT.close(),同时注意在异步操作完成后再执行关闭
修复后的MongoDB.js代码
import dotenv from "dotenv"; dotenv.config(); import { MongoClient, ServerApiVersion } from "mongodb"; export default class Mongodb { D_NAME = null; C_NAME = null; CLIENT = null; DB = null; URL = `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_HOSTNAME}/?retryWrites=true&w=majority`; constructor(database, collection) { this.D_NAME = database; this.C_NAME = collection; this.CLIENT = new MongoClient(this.URL, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, }, }); } // 改为异步方法 async conn() { try { // 等待连接完成 await this.CLIENT.connect(); this.DB = this.CLIENT.db(this.D_NAME).collection(this.C_NAME); console.log("Connected"); } catch (e) { console.log(e); throw e; // 抛出错误以便上层处理 } } async getData(query) { await this.conn(); // 等待连接建立 try { console.log("Get Data"); // 将游标转换为数组 return await this.DB.find(query).toArray(); } catch (e) { console.log(e); return e; } finally { // 可选:如果不需要保持连接,可在此关闭客户端 // await this.CLIENT.close(); } } async setNewData(data) { await this.conn(); // 等待连接建立 try { return await this.DB.insertOne(data); } catch (e) { console.log(e); return e; } finally { // 使用CLIENT关闭连接 await this.CLIENT.close(); } } }
修复后的router代码
import express from "express"; import bcrypt from "bcrypt"; import Mongodb from "../Modules/Mongodb.js"; const router = express.Router(); router.post("/", async(req, res) => { let db = new Mongodb("sample_analytics", "accounts"); console.log("test"); try { // 添加错误处理,捕获可能的连接或查询错误 let data = await db.getData(req.query); console.log(data); res.send(data); } catch (err) { res.status(500).send({ error: err.message }); } }); export { router };
内容的提问来源于stack exchange,提问作者Nariyao
相关产品推荐
相关产品推荐

