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

如何在React.js前端获取并展示MongoDB数据库中的集合名称

How to Display MongoDB Collection Names in React Frontend from Express Backend

Got it, let's break this down into two straightforward steps: updating your Express backend to add an endpoint that fetches all MongoDB collection names, then building a React component to call this endpoint and render the names.

Step 1: Update Your Express Backend to Add a Collections Endpoint

Your current backend already connects to MongoDB via Mongoose, so we just need to add a new API route that uses Mongoose's built-in methods to list all collections.

Add this new route to your existing backend code (inside the "API routes" section):

// Add this new route to fetch all collection names
app.get("/collections", async (req, res) => {
  try {
    // Fetch all collections from the connected database
    const collections = await mongoose.connection.db.listCollections().toArray();
    // Extract just the collection names from the response
    const collectionNames = collections.map(collection => collection.name);
    res.status(200).send(collectionNames);
  } catch (err) {
    console.error("Error fetching collections:", err);
    res.status(500).send("Failed to retrieve collection names");
  }
});

What this does:

  • mongoose.connection.db gives us direct access to the MongoDB database instance
  • listCollections().toArray() fetches all collection metadata and converts it to a JavaScript array
  • We map over the array to extract only the name property of each collection, then send that array as the response

Step 2: Build the React Frontend Component to Display Collections

Create a new React component (e.g., CollectionList.js) that fetches the collection names from your backend and renders them. We'll use React's useState to store the data and useEffect to trigger the fetch when the component mounts.

import { useState, useEffect } from 'react';

const CollectionList = () => {
  const [collectionNames, setCollectionNames] = useState([]);
  const [fetchError, setFetchError] = useState(null);

  useEffect(() => {
    const getCollections = async () => {
      try {
        // Replace with your backend URL (use environment variables in production!)
        const response = await fetch("http://localhost:9000/collections");
        if (!response.ok) throw new Error("Failed to fetch data");
        
        const data = await response.json();
        setCollectionNames(data);
      } catch (err) {
        setFetchError(err.message);
      }
    };

    getCollections();
  }, []);

  return (
    <div className="collection-list">
      <h2>Your MongoDB Collections</h2>
      
      {fetchError && <p className="error-message">Error: {fetchError}</p>}
      
      {collectionNames.length > 0 ? (
        <ul>
          {collectionNames.map((name, index) => (
            <li key={index}>{name}</li>
          ))}
        </ul>
      ) : (
        !fetchError && <p>Loading collections...</p>
      )}
    </div>
  );
};

export default CollectionList;

To use this component:

  • Import it into your main App.js (or any other parent component):
    import CollectionList from './CollectionList';
    
    function App() {
      return (
        <div className="App">
          <CollectionList />
        </div>
      );
    }
    
    export default App;
    

Important Notes:

  • CORS: Your backend already uses the cors middleware, so cross-origin requests from React (running on localhost:3000 by default) should work without issues.
  • Production Deployment: In production, replace the hardcoded http://localhost:9000 with your actual backend URL. Use environment variables (like process.env.REACT_APP_BACKEND_URL) to avoid hardcoding.
  • Error Handling: The component includes basic error handling to display issues if the fetch fails, which helps with debugging.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:17:41