πμ½λ 보λ¬κ°κΈ°
https://github.com/Sara-Jo/BeWild/tree/4a403567207e921de3dcceec4ded3685c08c7b8c
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const reviewSchema = new Schema({
body: String,
rating: Number
});
module.exports = mongoose.model("Review", reviewSchema);
const mongoose = require('mongoose');
const Review = require("./review");
const Schema = mongoose.Schema;
const CampgroundSchema = new Schema ({
title: String,
image: String,
price: Number,
description: String,
location: String,
reviews: [
{
type: Schema.Types.ObjectId,
ref: 'Review'
}
]
});
// Delete reviews when the campground is deleted
CampgroundSchema.post("findOneAndDelete", async function (doc) {
if (doc) {
await Review.deleteMany({
_id: {
$in: doc.reviews
}
});
}
});
module.exports = mongoose.model("Campground", CampgroundSchema);
// Review Post and Delete
app.post("/campgrounds/:id/reviews", validateReview, catchAsync(async(req, res) => {
const campground = await Campground.findById(req.params.id);
const review = new Review (req.body.review);
campground.reviews.push(review);
await review.save();
await campground.save();
res.redirect(`/campgrounds/${campground._id}`);
}));
app.delete("/campgrounds/:id/reviews/:reviewId", catchAsync(async(req, res) => {
const { id, reviewId } = req.params;
await Campground.findByIdAndUpdate(id, { $pull: { reviews: reviewId }});
await Review.findByIdAndDelete(req.params.reviewId);
res.redirect(`/campgrounds/${id}`);
}));