I'm building a simple MERN application, where users submit reviews about cafes. I'd like users to be able to click on a cafe name, the be directed to a page where all the reviews for that particular cafe are shown.
To do this, I need to filter through the reviews and return only the reviews pertaining to the specific cafe. So how do I give review documents from the same cafe a common ID? Or am I approaching this the wrong way? I did manage to fitler reviews based on Cafe name, but I feel that it's bad practice to do so.
Review post route and model
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 route and model
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
Here's the component that displays the list of cafes - where I want users to be able to click on a cafe, and be directed to the cafe's reviews.
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