调用Node.js自定义MongoDB查询模块返回undefined,请问问题出在哪?
问题排查与修复方案
核心错误点
getAll作为async函数没有显式返回查询结果对应的Promise,async函数无return语句时默认返回值为undefined的Promise,路由中await拿到的自然是undefined。- 代码混用
async/await和.then()回调逻辑,查询操作的返回值仅在.then()回调内部生效,没有传递到getAll函数的外层返回值中。 - 额外优化点:每次调用
getAll都新建数据库连接、查询后立即断开,高并发场景下性能损耗极大,建议全局复用数据库连接。
修正后代码
数据模块代码
async function getAll() { try { await mongoose.connect(config.mongoURL); const conn = mongoose.connection; const result = await conn.collection('healthdata').find({}).toArray(); console.log('=>Docs:', result); return result; } catch (err) { console.log(err); throw err; // 抛出错误供上层调用处理 } finally { mongoose.connection.close(); } } exports.getAll = getAll;
如果需要优化数据库连接复用,可将连接逻辑提到函数外部全局初始化,删除finally中的关闭连接逻辑即可。
路由调用代码
app.get("/", async (req, res) => { try { const docs = await db.getAll(); console.log("Result:", docs); res.render("index.html"); } catch (err) { // 可自定义错误响应逻辑 res.status(500).send('服务器异常'); } });
内容的提问来源于stack exchange,提问作者devops036 devops036
相关产品推荐
相关产品推荐

