0

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

1 Answer 1

1

I found the solution

JSON.stringify (imgArr)

It solved my problem

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.