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

通过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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:08:24