【发布时间】:2021-04-16 04:27:48
【问题描述】:
我正在构建一个简单的 MERN 应用程序,用户可以在其中提交有关咖啡馆的评论。我希望用户能够单击咖啡馆名称,然后被定向到显示该特定咖啡馆的所有评论的页面。
为此,我需要过滤评论并仅返回与特定咖啡馆有关的评论。那么如何为同一家咖啡馆的审核文件提供一个通用 ID?还是我以错误的方式接近这个?我确实设法根据咖啡馆名称调整评论,但我觉得这样做是不好的做法。
查看发布路线和模型
app.post('/api/add-review',(req,res) => {
const review = new Review(req.body)
review.save()
.then(() => {
console.log('review successfully posted')
res.status(200)
})
.catch(err => {
console.log(err)
})
})
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const reviewSchema = new Schema({
userName:String,
stars:String,
title:String,
photo:String,
blurb:String,
cafe:String
}, {timestamps:true})
const Review = mongoose.model('reviews', reviewSchema)
module.exports = Review
Cafe GET 路径和模型
app.get('/api/all-cafes', (req,res) => {
Cafe.find()
.then((result) => {
res.send(result)
})
.catch(err => {
console.log(err)
})
})
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const cafeSchema = new Schema({
cafeName:String,
photoURL:String,
}, {timestamps:true})
const Cafe = mongoose.model('cafes', cafeSchema)
module.exports = Cafe
这是显示咖啡馆列表的组件 - 我希望用户能够点击咖啡馆并被引导到咖啡馆的评论。
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import Cafe from './Cafe'
const CafeList = () => {
const [cafes, setCafe] = useState([])
useEffect(() => {
axios.get('/api/all-cafes')
.then(cafe => {
setCafe(cafe.data)
})
.catch(err => {
console.log(err)
})
},[])
return(
<div className = 'cafe-container-container'>
<h2>Cafes</h2>
<Cafe cafes = {cafes}/>
</div>
)
}
export default CafeList
import React from 'react'
import {Link} from 'react-router-dom'
const Cafe = (props) => {
const {cafes} = props
return(
<div>
{
cafes.map(cafe =>{
const {cafeName,photoURL} = cafe
return (
<Link to = {`/cafe-reviews/${cafeName}`} style={{ textDecoration: 'none' }} >
<div className = 'cafe-container'>
<h2>{cafeName}</h2>
<img src = {photoURL}></img>
</div>
</Link>
)
})
}
</div>
)
}
export default Cafe
【问题讨论】:
标签: reactjs mongodb express mongoose