Uploading multiple files to aws-s3 using Multer (Object with an other array of objects inside)

139 views Asked by At

I'm trying to upload multiple images to my aws-s3 using multer. The problem I'm facing is I managed to upload the first backgroundImage which is outside the second array what I mean. Here is my structure

const QuizSchema = new mongoose.Schema({
  title: { type: String, required: true, unique: true },
  description: { type: String },
  backgroundImage: { type: String }, 
  questionList: [questionSchema]
})

const questionSchema = new mongoose.Schema({
  questionType: {
    type: String,
    enum: ["True/False", "Quiz"],
    required: true,
  },
  pointType: {
    type: String,
    enum: ["Standard", "Double"],
    required: true,
  },
  backgroundImage: { type: String },
  questionIndex: { type: Number, required: true },
});

I removed some of the structures to make it more readable. So I managed to upload and save the URL of the the backgroundImage. But i cant upload the backgroundImage for Each question.

My router:

router.post(
  "/createQuiz",
  uploadFile.single("backgroundImage"),
  verifyToken,
  createQuiz
);

My upload file middleWare:

const storage = multer.memoryStorage();
dotenv.config();
export const uploadFile = multer({ storage });

My quiz Controller

// Creating a random image name
const randomImageName = (bytes = 32) =>
  crypto.randomBytes(bytes).toString("hex");

const imageName = randomImageName();

// Creating a new Quiz
export const createQuiz = async (req, res) => {
  const user = await User.findById(req.user.id);

  //Resize Image
  const buffer = await sharp(req.file.buffer)
    .resize({ height: 500, width: 500, fit: "contain" })
    .toBuffer();

  const params = {
    Bucket: bucketName,
    Key: imageName,
    Body: buffer,
    ContentType: req.file.mimetype,
  };

  const command = new PutObjectCommand(params);
  await s3.send(command);

  const { title, description, categories, questionList } = req.body;
  const backgroundImage = imageName;

  const quiz = new Quiz({
    title,
    description,
    backgroundImage,
    categories,
    creatorId: req.user.id,
    creatorName: user.firstName + " " + user.lastName,
    numberOfQuestions: questionList.length,
    questionList,
    dateCreated: new Date().toISOString(),
  });
  try {
    const newQuiz = await quiz.save();
    res.status(201).json(newQuiz);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

Thanks in Advance, P.S i deleted whatever i tried for questionList since it was not working.

UPDATED

   const quizData = new FormData();
    quizData.append("title", values.title);
    quizData.append("description", values.description);
    quizData.append("categories", values.categories);

    // append the background image to the quiz data
    quizData.append("backgroundImage", values.backgroundImage);
    // Append each question's backgroundImage to the quiz data
    values.questionList.forEach((question, index) => {
      quizData.append(`backgroundImage${index}`, question.backgroundImage);
    });

    // Append the questionList array as a JSON string
    quizData.append("questionList", JSON.stringify(values.questionList));

    // loop through the questionList array and create a FormData object for each question
    // values.questionList.forEach((question, index) => {
    //   const questionData = new FormData();
    //   questionData.append("question", question.question);
    //   questionData.append("questionType", question.questionType);
    //   questionData.append("pointType", question.pointType);
    //   questionData.append("answerTime", question.answerTime);
    //   questionData.append("questionIndex", question.questionIndex);
    //   questionData.append("backgroundImage", question.backgroundImage);

    //   // append the question data to the quiz data
    //   quizData.append(`questionList[${index}]`, questionData);
    // });

Getting an error MulterError: Unexpected field (Server)

0

There are 0 answers