RESTRUCTURING REVIEWS
HERE WE MERGE THE PARENT AND CHILD ROUTE TO PASS THE PARAMETERS TO THE CHILD ROUTE.
PARENT ROUTE IS :
app.use("/listings/:id/reviews", reviews);
CHILD ROUTE IS:
router.delete(
"/:reviewId",
wrapAsync(async (req, res) => {
REVIEWS.JS
const express = require("express");
const router = express.Router({ mergeParams: true });
const wrapAsync = require("../utils/wrapAsync.js");
const ExpressError = require("../utils/ExpressError.js");
const { listingSchema, reviewSchema } = require("../schema.js");
const Review = require("../models/review.js");
const Listing = require("../models/listing.js");
const ValidateReview = (req, res, next) => {
let { error } = reviewSchema.validate(req.body);
if (error) {
let errMsg = error.details.map((el) => el.message).join(",");
throw new ExpressError(400, errMsg);
} else {
next();
}
};
// REVIEWS
router.post(
"/",
ValidateReview,
wrapAsync(async (req, res) => {
let { id } = req.params;
let listing = await Listing.findById(id);
let newRev = new Review(req.body.review);
console.log(newRev);
await newRev.save();
listing.reviews.push(newRev);
await listing.save();
console.log("review saved");
res.redirect(`/listings/${id}`);
})
);
// DELETE REVIEW
router.delete(
"/:reviewId",
wrapAsync(async (req, res) => {
let { id, reviewId } = req.params;
await Listing.findByIdAndUpdate(id, { $pull: { reviews: reviewId } });
await Review.findByIdAndDelete(reviewId);
res.redirect(`/listings/${id}`);
})
);
module.exports=router;
APP.JS


Comments
Post a Comment