Node.js连接MongoDB失败控制台输出undefined,如何正常查询员工数据?
问题原因
你的代码核心问题是异步逻辑执行顺序错误:find().toArray()是异步回调方法,你在finally代码块中直接关闭数据库连接,不等查询请求返回结果就断开了连接,因此无法拿到查询数据,控制台输出undefined。另外你也没有对各个环节的错误参数做捕获处理,很难定位问题。
修正方案
回调写法适配
将关闭连接的逻辑移到toArray的回调函数内,确保查询完成后再断开连接,同时补充错误处理:
// Connect using a MongoClient instance const MongoClient = require("mongodb").MongoClient; // Connection url const url = "mongodb://localhost:27017"; // Database Name const dbName = "test"; // Connect using MongoClient const mongoClient = new MongoClient(url); mongoClient.connect(function (err, client) { // 捕获连接错误 if (err) { console.error('数据库连接失败:', err) return client.close() } const db = client.db(dbName); db.collection("employeeDetails") .find({}) .toArray(function (err, res) { // 捕获查询错误 if (err) { console.error('数据查询失败:', err) } else { console.log(res); } // 查询完成后再关闭连接 client.close(); }); });
更推荐的async/await写法(适配MongoDB Node.js驱动3.x及以上版本)
用同步写法逻辑处理异步流程,可读性和可维护性更高:
const MongoClient = require("mongodb").MongoClient; const url = "mongodb://localhost:27017"; const dbName = "test"; async function getEmployeeData() { const client = new MongoClient(url); try { await client.connect(); const db = client.db(dbName); const result = await db.collection("employeeDetails").find({}).toArray(); console.log(result); } catch (err) { console.error('操作出错:', err); } finally { await client.close(); } } getEmployeeData();
额外检查项
- 确认本地MongoDB服务已正常启动,27017端口未被其他程序占用
- 确认
test数据库下存在employeeDetails集合,且集合内已插入对应数据
内容的提问来源于stack exchange,提问作者pranayrebel
相关产品推荐
相关产品推荐

