Reputation: 41
I am trying to build an app which will have help users put menus. But after sending a post request to add the menu in Postman, it gives a blank message with 500 internal server error. The request I am sending also fulfills the model but for some reason I still get the error.
The controller code-
import mongoose from "mongoose";
import Menu from "../model/Menu";
import User from "../model/User";
export const getMenu=async(req,res,next)=>{
let menus;
try{
menus=await Menu.find().populate('user');
}catch(err){
return console.log(err)
}
if(!menus){
return res.status(404).json({message:"no menu found"});
}
return res.status(200).json({menus})
}
export const addMenu=async(req,res,next)=>{
const {title,price,image,category,user}=req.body;
let existingUser;
try{
existingUser=await User.findById(user);
}catch(err){
return console.log(err)
}
if(!existingUser){
return res.status(400).json({message:"Unabel to find user by this id"})
}
const menu= new Menu({
title,
price,
image,
category,
user,
});
try{
const session=await mongoose.startSession();
session.startTransaction();
await menu.save({session});
existingUser.menus.push(menu);
await existingUser.save({session})
await session.commitTransaction();
}catch(err){
return res.status(500).json({message:err})
}
return res.status(200).json({menu})
};
The model code-
import mongoose from "mongoose";
const Schema=mongoose.Schema;
const menuSchema=new Schema({
title:{
type:String,
required:true,
},
price:{
type:Number,
required:true,
},
image:{
type:String,
required:true,
},
category:[{type:String,ref:"Category",required:true}],
user:{
type:mongoose.Types.ObjectId,
ref:"User",
required:true,
},
});
export default mongoose.model("Menu",menuSchema);
Upvotes: 0
Views: 1089
Reputation: 2031
It's returning 500 because you are returning a 500 in the catch block. Log the error and it will tell you why the error is happening.
Upvotes: 1