You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:54:02