通过Mongoose连接MongoDB后无法获取数据,求排查方案
Mongoose连接MongoDB后无法输出查询数据的问题排查
问题描述
按照教程通过Mongoose连接MongoDB,但console.log(data)没有任何输出。
代码实现
const mongoose = require('mongoose'); const mongoURI = 'mongodb+srv://gofood:xxxxxxxxx@cluster0.bgpaa3e.mongodb.net/?retryWrites=true&w=majority' process.on('uncaughtException', err => { console.log('UNCAUGHT EXCEPTION! 💥 Shutting down...'); console.log(err.name, err.message); process.exit(1); }); async function called(){ console.log('Connection successful!'); const fetched_data = await mongoose.connection.db.collection("foodCategory"); console.log('reaching here?????') fetched_data.find({}).toArray(function(err, data){ if(err) console.log(err); else console.log(data);}) }; const mongoDB = async () => { await mongoose .connect(mongoURI, { useNewUrlParser: true }) .then(() => called()) } module.exports = mongoDB;
运行输出
[nodemon] starting `node .\index.js` Example app listening on port 5000 Connection successful! reaching here?????
教程中数据会立即显示,请问哪里操作有误?
问题原因及解决方法
未指定目标数据库:你的连接字符串没有指定要操作的具体数据库,Mongoose连接集群后不会自动切换到业务库,导致查询的
foodCategory集合无法定位。修改连接字符串,在末尾添加数据库名称(替换成你实际的数据库名):const mongoURI = 'mongodb+srv://gofood:xxxxxxxxx@cluster0.bgpaa3e.mongodb.net/你的数据库名?retryWrites=true&w=majority'集合名称不匹配:确认MongoDB中实际存在
foodCategory集合,注意集合名称区分大小写;如果集合不存在,find({})会返回空数组且无报错。回调写法的排查盲区:建议把回调版的
toArray改成async/await写法,更直观且便于捕获错误:async function called(){ console.log('Connection successful!'); const db = mongoose.connection.db; // 打印当前数据库,确认是否连接到目标库 console.log('当前连接的数据库:', db.databaseName); const fetched_data = db.collection("foodCategory"); console.log('reaching here?????') try { const data = await fetched_data.find({}).toArray(); console.log(data); } catch (err) { console.error('查询错误:', err); } };权限或网络问题:检查数据库用户是否拥有该集合的读取权限,同时确认当前网络能正常访问MongoDB Atlas集群(可在Atlas控制台直接查询该集合验证数据是否存在)。
内容的提问来源于stack exchange,提问作者Alpha
相关产品推荐
相关产品推荐

