I am learning from a udemy course where we build a Yelp like site but for campgrounds.
I am getting a problem every time I try to update the campground.
Error: "campground" is required
at module.exports.validateCampground (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/middleware.js:19:9)
at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:137:13)
at module.exports.isLoggedIn (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/middleware.js:12:3)
at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:137:13)
at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:131:14)
at Route.dispatch (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
at /Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/index.js:281:22
I looked through the relevant methods and schemas but cannot find anything that is causing the error. Can someone please help?
My Joi schema looks like this
const Joi = require('joi');
module.exports.campgroundSchema = Joi.object({
campground: Joi.object({
title: Joi.string().required(),
price: Joi.number().required().min(0),
//image: Joi.string(),
location: Joi.string().required(),
description: Joi.string().required()
}).required()
});
The code for updating campground:
module.exports.updateCampground = async (req, res) => {
const { id } = req.params;
const campgrounds = await campground.findByIdAndUpdate(id, { ...req.body.campground });
const imgs = req.files.map((f) => ({ url: f.path, filename: f.filename }));
campgrounds.images.push(...imgs);
await campgrounds.save();
req.flash('success', 'Successfully updated Campground');
res.redirect(`/campgrounds/${campgrounds._id}`);
};
The validateCampground method is like this:
module.exports.validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body);
if (error) {
const msg = error.details.map((el) => el.message).join(',');
throw new ExpressError(msg, 400);
} else {
next();
}
};
Can anyone please help?
The validateCampground method should be like this:
const { error } = campgroundSchema.validate(req.body.campground);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.