Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance Campground Schema with Validation, Timestamps, and Improved Error Logging #363

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 35 additions & 12 deletions models/campground.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
// Import necessary modules
const mongoose = require('mongoose');
const Review = require('./review'); // Model for associated reviews
const Schema = mongoose.Schema; // Extract Schema for easier usage
Comment on lines -2 to -4
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

undo the deletion

const mongoose = require('mongoose');
const Review = require('./review'); // Model for associated reviews
const Schema = mongoose.Schema; // Extract Schema for easier usage

// Route to handle new campground creation
router.post('/campgrounds', async (req, res, next) => {
try {
const campground = new Campground(req.body.campground);
await campground.save();
res.redirect(`/campgrounds/${campground._id}`);
} catch (err) {
// Check if the error is a validation error
if (err.name === 'ValidationError') {
// Render the form again with an error message
req.flash('error', 'Title must be at least 3 characters.');
return res.redirect('/campgrounds/new');
}
next(err); // Pass any other errors to the default error handler
}
});

module.exports = router;

// Define the Image schema
const ImageSchema = new Schema({
Expand All @@ -14,13 +32,13 @@ ImageSchema.virtual('thumbnail').get(function () {
return this.url.replace('/upload', '/upload/w_200');
});

// Define options to ensure virtuals are included in JSON output
const opts = { toJSON: { virtuals: true } };
// Define options to ensure virtuals are included in JSON output and add timestamps
const opts = { toJSON: { virtuals: true }, timestamps: true };

// Define the Campground schema
const CampgroundSchema = new Schema(
{
title: { type: String, required: true }, // Campground title
title: { type: String, required: true, minlength: 3 }, // Minimum title length of 3 characters
images: [ImageSchema], // Array of images using ImageSchema
geometry: {
type: {
Expand All @@ -30,10 +48,14 @@ const CampgroundSchema = new Schema(
},
coordinates: {
type: [Number], // Array of numbers representing coordinates [longitude, latitude]
required: true
required: true,
validate: {
validator: (coords) => coords.length === 2,
message: "Coordinates must contain longitude and latitude"
}
}
},
price: { type: Number, required: true }, // Campground price
price: { type: Number, required: true, min: 0 }, // Price must be positive
description: { type: String, required: true }, // Description of the campground
location: { type: String, required: true }, // Location of the campground
author: {
Expand All @@ -48,7 +70,7 @@ const CampgroundSchema = new Schema(
}
]
},
opts // Pass options to include virtuals in JSON responses
opts // Pass options to include virtuals in JSON responses and add timestamps
);

// Virtual property to generate a small popup HTML snippet for use in maps or previews
Expand All @@ -62,11 +84,12 @@ CampgroundSchema.virtual('properties.popUpMarkup').get(function () {
CampgroundSchema.post('findOneAndDelete', async function (doc) {
if (doc) {
try {
await Review.deleteMany({
const result = await Review.deleteMany({
_id: { $in: doc.reviews }
});
console.log(`Successfully deleted ${result.deletedCount} associated reviews for campground ${doc._id}`);
} catch (err) {
console.error('Error deleting associated reviews:', err);
console.error(`Error deleting associated reviews for campground ${doc._id}:`, err);
}
}
});
Expand Down