There is a database schema defined in the code below:
const mongoose = require("mongoose");
const FormCourse_schema = new mongoose.Schema({
FormCourse: {
type: mongoose.Schema.Types.ObjectId,
ref: "cards",
required: true,
},
date: { type: String },
file: { type: String },
video: { type: String },
pdf: { type: String },
});
module.exports = mongoose.model("FormCourse", FormCourse_schema);
The controller function for posting data is shown below:
exports.post_FormCourse = async (req, res, next) => {
try {
// if (!req.userId) return res.status(406).json({ message: "Unauthenticated" });
const FormCourse_id = req.body.FormCourse_id;
const isFormCourse = FormCourse.findById(FormCourse_id);
if (isFormCourse.length < 1) res.status(202).json("FormCourse not found");
const course = new FormCourse({
date: req.body.date,
file: req.file.path,
video: req.file.path,
pdf: req.file.path,
});
const result = await course.save();
res.status(200).send({
result: result,
request: {
type: "GET",
url: "localhost:3002/form/" + result._id,
},
});
} catch (error) {
res.status(404).json({ message: "invalid id", error: err });
}
};
A router is defined below with endpoints for POST, PATCH, and DELETE:
const express = require("express");
const router = express.Router();
const FormCourses = require("../controllers/formCourses");
const checkAuth = require("../middleware/checkAuth");
const multer = require("multer");
// Multer configurations for different file types
// Endpoint definitions
module.exports = router;
The main app file includes error handling for 500 errors:
const express = require("express");
const app = express();
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");
// Middleware and router configurations
// Handling errors
module.exports = app;
This code has a testing scenario for a 500 error with Postman: There might be an error due to multiple fields for uploading in the router.post method. How can this be resolved?