如何通过Mongoose将MongoDB数据传递至React的App.jsx?
问题描述
我已经通过Mongoose在App.js中连接MongoDB,可在App.js中对数据库进行读写操作,但无法将通过函数获取的数据传递至App.jsx以在React中渲染。当前我使用自行创建的restaurants.js文件中的对象进行渲染,该文件是我搭建结构时用于测试的数据源。刚接触React和MongoDB,已用尽现有JavaScript函数知识仍无法解决问题,尝试使用module.exports也无法返回数据,恳请帮助。
相关代码
后端代码(App.js)
const mongoose = require('mongoose'); mongoose.connect("mongodb://127.0.0.1:27017/restaurantsDB") const restaurantSchema = new mongoose.Schema({ name: String, rating: Number, image: String, categories: [], restaurantID: Number, avgDeliveryTime: Number }); const Restaurant = mongoose.model("Restaurant", restaurantSchema); const restaurant = new Restaurant({ name: "Death Star Burgers", rating: 4, image: "/assets/restaurant photos/rectangle 150.png", categories: ["burgers","fries"], avgDeliveryTime: 30 }); Restaurant.find(function(err,all){ all.forEach(function(x){ console.log(x.name) }) })
前端代码(App.jsx)
import React from 'react'; import RestaurantCard from './RestaurantCard' import Restaurant from '../restaurants' function createRestaurantCard(restaurant){ return <RestaurantCard key = {restaurant.id} id = {restaurant.id} name={restaurant.name} image = {restaurant.image} ratings = {restaurant.ratings} categories = {restaurant.categories} averageDeliveryTime = {restaurant.averageDeliveryTime} /> } function App() { return <div className='restaurant-grid'> {Restaurant.map(createRestaurantCard)} </div> } export default App;
测试数据文件(restaurants.js)
const restaurantData=[ { id: 0, name: "Hyper Burgers", image: "/assets/restaurant photos/rectangle 150.png", categories: "burgers, chicken", ratings: 5, averageDeliveryTime: "30min" }, { id: 1, name: "Death Steak", image: "/assets/restaurant photos/steak.png", categories: "steaks, chicken", ratings: 4, averageDeliveryTime: "40min" }, { id: 2, name: "Dynasty Chinese Restaurant", image: "/assets/restaurant photos/chinese.png", categories: "rice, noodles", ratings: 5, averageDeliveryTime: "15min" }, { id: 3, name: "Lefmagir Doner", image: "/assets/restaurant photos/wrap.png", categories: "wrap, sis kebab", ratings: 2, averageDeliveryTime: "50min" } ] export default restaurantData;
解决步骤
1. 后端搭建API接口(依赖Express)
前端和后端是独立运行的进程,不能直接调用后端的Mongoose方法,必须通过HTTP接口传递数据。
首先安装Express:
npm install express
修改后端App.js,添加接口逻辑:
const mongoose = require('mongoose'); const express = require('express'); const app = express(); const port = 3001; // 与前端开发服务器端口(默认3000)区分开 // 连接数据库 mongoose.connect("mongodb://127.0.0.1:27017/restaurantsDB") .then(() => console.log('数据库连接成功')) .catch(err => console.log(err)); // 定义Schema和Model const restaurantSchema = new mongoose.Schema({ name: String, rating: Number, image: String, categories: [], restaurantID: Number, avgDeliveryTime: Number }); const Restaurant = mongoose.model("Restaurant", restaurantSchema); // 可选:首次运行时保存测试数据到数据库 // restaurant.save(); // 定义获取餐厅数据的API接口 app.get('/api/restaurants', async (req, res) => { try { const allRestaurants = await Restaurant.find({}); // 转换字段格式,匹配前端需要的结构 const formattedData = allRestaurants.map(item => ({ id: item.restaurantID || item._id, // 用自定义ID或MongoDB自带ID name: item.name, image: item.image, ratings: item.rating, // 统一后端rating与前端ratings字段名 categories: item.categories.join(', '), // 数组转字符串 averageDeliveryTime: `${item.avgDeliveryTime}min` // 数字转带单位字符串 })); res.json(formattedData); } catch (err) { res.status(500).json({ error: err.message }); } }); // 启动后端服务器 app.listen(port, () => { console.log(`后端服务器运行在 http://localhost:${port}`); });
2. 前端请求接口并渲染
修改App.jsx,使用React的useState和useEffect钩子请求后端接口,获取数据后渲染:
import React, { useState, useEffect } from 'react'; import RestaurantCard from './RestaurantCard' function createRestaurantCard(restaurant){ return <RestaurantCard key = {restaurant.id} id = {restaurant.id} name={restaurant.name} image = {restaurant.image} ratings = {restaurant.ratings} categories = {restaurant.categories} averageDeliveryTime = {restaurant.averageDeliveryTime} /> } function App() { const [restaurants, setRestaurants] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // 组件挂载时请求后端接口 useEffect(() => { fetch('http://localhost:3001/api/restaurants') .then(response => { if (!response.ok) throw new Error('请求失败'); return response.json(); }) .then(data => { setRestaurants(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); // 加载状态与错误状态处理 if (loading) return <div>加载中...</div>; if (error) return <div>出错了:{error}</div>; return <div className='restaurant-grid'> {restaurants.map(createRestaurantCard)} </div> } export default App;
3. 运行项目
- 启动后端服务器:
node App.js - 启动前端开发服务器(如使用Create React App):
npm start
此时前端即可从后端获取MongoDB中的餐厅数据并渲染。
内容的提问来源于stack exchange,提问作者Abdulfatah Sanni
相关产品推荐
相关产品推荐

