Home > Enterprise >  Mongoose Schema Error: "Cast to string failed for value"
Mongoose Schema Error: "Cast to string failed for value"

Time:11-04

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

CodePudding user response:

I found the solution

JSON.stringify (imgArr)

It solved my problem

  • Related