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

React无法展示从MongoDB通过Node/Express获取的数据问题

MERN栈获取集合数据返回空数组问题排查

刚接触MERN栈,尝试从MongoDB集合获取数据时,前端控制台返回长度为0的数组,无法展示数据。数据库连接正常无报错,但数据无法正确返回。以下是相关代码:

前端App.tsx代码

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {
  const [admin, setadmin] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('http://localhost:4001/getAdmin')
      .then(response => {
        console.log(response.data);
        setadmin(response.data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div className='mt-10 ml-10'>
      <table className='border border-black px-10 py-10'>
        <thead>
          <tr>
            <th>Username</th>
            <th>Password</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {admin.map(admindata => (
            <tr key={admindata._id}>
              <td>{admindata.username}</td>
              <td>{admindata.password}</td>
              <td>{admindata.name}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default App;

后端index.js代码

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const AdminInfoModel = require('./models/AdminInfoModel');

const app = express();
app.use(cors());
app.use(express.json());
const PORT = 4001;

mongoose.connect("mongodb://127.0.0.1:27017/MESAA")
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Error connecting to MongoDB:', err));

app.get('/getAdmin', async (req, res) => {
    try {
        const adminData = await AdminInfoModel.find();
        res.json(adminData);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

模型文件AdminInfoModel.js代码

const mongoose = require('mongoose');

const AdminInfoSchema = new mongoose.Schema(
    {
        _id: mongoose.Schema.Types.ObjectId,
        username: String,
        password: String,
        name: String
    }
);

const AdminInfoModel = mongoose.model('AdminInfo', AdminInfoSchema);

module.exports = AdminInfoModel;

问题排查与解决方法

1. 检查集合名称是否匹配

Mongoose默认会将模型名转换为复数小写形式的集合名,比如AdminInfo模型对应的集合名是admininfos,而非AdminInfo。

  • 打开MongoDB Compass或使用mongo命令行工具,确认MESAA数据库中存在的集合名称是否为admininfos;
  • 如果你的集合名是AdminInfo(单数或首字母大写),需在定义模型时显式指定集合名:
    const AdminInfoModel = mongoose.model('AdminInfo', AdminInfoSchema, 'AdminInfo');
    

2. 检查_id字段类型是否一致

你在Schema中手动定义了_id为ObjectId类型,但如果数据库中现有文档的_id是字符串或其他类型,find()查询会无法匹配到数据:

  • 建议去掉Schema中手动定义的_id字段,让Mongoose自动生成ObjectId类型的_id:
    const AdminInfoSchema = new mongoose.Schema(
        {
            username: String,
            password: String,
            name: String
        }
    );
    
  • 若必须保留自定义_id,需确保数据库中所有文档的_id均为ObjectId类型(可通过MongoDB Compass查看字段类型)。

3. 验证数据库中是否存在数据

直接在MongoDB中执行查询语句,确认集合内是否有数据:

# 进入MongoDB命令行
mongo
# 切换到MESAA数据库
use MESAA
# 查询admininfos集合(或你的实际集合名)中的数据
db.admininfos.find()

如果查询结果为空,说明集合内没有数据,需要先插入测试数据。

4. 确认数据库连接的正确性

检查mongoose.connect中的数据库名称MESAA是否正确,确保你连接的是包含目标集合的数据库。

内容的提问来源于stack exchange,提问作者Nicoo Repz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:08:25