Reputation: 1
I am trying to make a Create Routeand this is my code:
router.post("/", middleware.isAdmin, upload.single('image'), function(req,res){
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if(err) {
req.flash('error', err.message);
return res.redirect('back');
}
// add cloudinary url for the image to the meal object under image property
req.body.meal.image = result.secure_url;
// add image's public_id to meal object
req.body.meal.imageId = result.public_id;
// add author to meal
req.body.meal.author = {
id: req.user._id,
username: req.user.username
}
Meal.create(req.body.meal, function(err, meal) {
if (err) {
req.flash('error', err.message);
return res.redirect('back');
}
res.redirect('/meals/' + meal.id);
});
});
});
And in my model:
var mongoose = require("mongoose");
var mealSchema = new mongoose.Schema({
name: String,
image: String,
imageId: String,
description: String,
price: String,
author:{
id:{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
});
module.exports = mongoose.model("Meal", mealSchema);
When I try to add a new meal the server disconnects and I this error:
TypeError: Cannot set property 'image' of undefined at /Users/talalsy/Desktop/Capital_Sandwich/routes/meals.js:44:27 at /Users/talalsy/Desktop/Capital_Sandwich/node_modules/cloudinary/lib/utils/index.js:1073:12 at IncomingMessage. (/Users/talalsy/Desktop/Capital_Sandwich/node_modules/cloudinary/lib/uploader.js:402:9) at IncomingMessage.emit (events.js:327:22) at endReadableNT (_stream_readable.js:1221:12) at processTicksAndRejections (internal/process/task_queues.js:84:21)
What might be the problem?
Upvotes: 0
Views: 740
Reputation: 341
Probably you're not passing meal object in the request or you're misspelling it or some issue like but the error is sure that you're not getting the meal in req.body.
Upvotes: 0