DEV Community

Code_Regina
Code_Regina

Posted on

|YelpCamp| Adding The Reviews Model

                -Defining The Review Model 
                -Adding The Review Form 
                -Creating Reviews 
                -Validating Reviews 
                -Displaying Reviews
                -Styling Reviews
Enter fullscreen mode Exit fullscreen mode

Defining The Review Model

This is the ability to add in a form for a new review.

Basic schema for review form


const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

const reviewSchema = new Schema({
   body: String, 
   rating: Number
 }); 

module.exports = mongoose.model('Review' reviewSchema); 

Enter fullscreen mode Exit fullscreen mode

Adding The Review Form

Modifiy the show.ejs file

add

<form action="">
<div class="mb-3">
  <label class="form-label" for="rating">Rating</label>
  <input type="range" min="1" max="5" name="review[rating]" id="rating">
  <textarea class="form-control" name="review[body]" id="body" cols="30" rows="10"></textarea>


Enter fullscreen mode Exit fullscreen mode

Leave a review

Alt Text

Alt Text

Alt Text

Creating Reviews

Creating the reviews route

 app.post('/campgrounds/:id/reviews', catchAsync(async(req, res) => {
  const campground = await Campground.findById(req.params.id);
  const review = new Review(req.body.review); 
  campground.reviews.push(reviews);
  await review.save();
  await campground.save(); 
  res.redirect(`/campgrounds/${campground._id`);
}
)); 

Enter fullscreen mode Exit fullscreen mode

Validating Reviews

Adding in client-side validation

within the schemas.js
add

module.exports.reviewSchema = Joi.object({
   review: Joi.object({
      rating: Joi.number().required(), 
      body:  Joi.string().required()
  })

 })

Enter fullscreen mode Exit fullscreen mode

Displaying Reviews

Within show.ejs
add

Alt Text

Alt Text

Styling Reviews

Alt Text

Top comments (0)