skip to Main Content

I have an error when i try to post this schema data into Form.js. Mongoose schema looks like this:

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

Logic for creating post is like this:

export const createPost = async (req, res) => {
    const post = req.body;

    const newPost = new PostMessage(post);

    try {
        await newPost.save();

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

I’m uploading image as String and I’m converting image using base64 from React like this-

import FileBase from 'react-file-base64';
<div className={classes.fileInput}><FileBase type="file" multiple="false" onDone={(base64) => setPostData({ ...postData, selectedFile: base64})}/></div>

When I try to submit form, I get error like –
{"message":"PostMessage validation failed: selectedFile: Cast to string failed for value

2

Answers


  1. Chosen as BEST ANSWER

    Found the answer, I was missing {} brackets aroung hte base64 after the onDone. so it should be like:

    <div className={classes.fileInput}><FileBase type="file" multiple={false} onDone={({ base64 }) => setPostData({ ...postData, selectedFile: base64 })} /></div>


  2. You missed the curly braces around base64 in onDone={({ base64 }).

    yes you must add {} to base64 I tested it and it works !!!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search