Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Mongoose Schema Error: "Cast to string failed for value"

hi guys i have an error when i try to send array of string with Mongoose Schema its work ok for the tags and not for the selectedFile..

Mongoose Schema:

import mongoose from "mongoose";

const postSchema = mongoose.Schema({
  title: String,
  message: String,
  name: String,
  creator: String,
  tags: [String],
  selectedFile: [String],
  likes: {
    type: [String],
    default: [],
  },
  comments: { type: [String], default: [] },
  createdAt: {
    type: Date,
    default: new Date(),
  },
});

const PostMessage = mongoose.model("PostMessage", postSchema);

export default PostMessage;

controller.js

export const createPost = async (req, res) => {
  const post = req.body;
  console.log(post);
  const newPostMessage = new PostMessage({
    ...post,
    creator: req.userId,
    createdAt: new Date().toISOString(),
  });
  try {
    await newPostMessage.save();

    res.status(201).json(newPostMessage);
  } catch (error) {
    res.status(409).json({ message: error.message });
  }
};

Form.js

const onChange = async (event) => {
    dispatch({ type: START_LOADING });
    let imgArr = "";
    let obj = event.target.files;
    for (let i = 0; i < obj.length; i++) {
      try {
        const file = obj[0];
        const image = await resizeFile(file);
        imgArr.push(image);
      } catch (err) {
        console.log(err);
      }
    }
    setPostData({ ...postData, selectedFile: ["imgArr"] });
    dispatch({ type: END_LOADING });
  };

for the test i put dammy value of ["imgArr"] and i got this error message: "PostMessage validation failed: selectedFile: Cast to string failed for value "[ 'imgArr' ]" (type Array) at path "selectedFile""

what i can do ? remember for the tags its work he accept array of string

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I found the solution

JSON.stringify (imgArr)

It solved my problem

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!