Express Node.js项目MongoDB异步操作返回undefined问题求助
问题原因
- 核心问题是
getData函数没有返回Promise对象。你在getData内部调用的mongoClient.connect是回调风格API,回调函数内部的return Mainresult只会将值返回给回调本身,不会作为外层getData函数的返回值。所以Express接口中await mongoDb.getData()实际等待的是undefined,自然拿不到查询结果。 - 异步执行顺序错位:回调函数的执行晚于外层
getData的返回,所以你会看到控制台先打印After hitting the Mongo,之后才会输出MongoDB的查询结果。 - 代码混用
await和.then()链式调用,写法冗余容易出现逻辑漏洞,且没有处理mongoClient.connect的连接错误。
修复方案
1. 重写MongoDbConnectivity.js
使用MongoDB驱动原生支持的Promise风格API,替换回调写法,保证getData返回可被等待的Promise:
// Connect using a MongoClient instance const MongoClient = require("mongodb").MongoClient; const logger = require("./loggers"); // Connection url const url = "mongodb://localhost:27017"; // Database Name const dbName = "test"; // Connect using MongoClient const mongoClient = new MongoClient(url); async function getData() { try { // 用await等待连接完成,替换回调写法 await mongoClient.connect(); const db = mongoClient.db(dbName); // 去掉冗余的then链式调用,直接await查询结果 const Mainresult = await db.collection("employeeDetails").find({}).toArray(); console.log(Mainresult); return Mainresult; } catch (err) { logger.errorLog(err); console.log(err); // 抛出错误让外层接口可以捕获处理 throw err; } finally { // 确保连接正常关闭 await mongoClient.close(); } } module.exports.getData = getData;
2. 给Express接口增加错误处理
避免查询出错时服务无响应:
app.get("/getEmployees",async function (req, res) { try { console.log("before hitting the Mongo"); var employeeData = await mongoDb.getData(); console.log("After hitting the Mongo"); console.log("from Node:" + employeeData); res.send(employeeData); } catch (e) { res.status(500).send({error: '数据查询失败'}) } });
内容的提问来源于stack exchange,提问作者pranayrebel
相关产品推荐
相关产品推荐

