Sequelize ValidationError [SequelizeValidationError] cannot be an array or an object

Viewed 18

I'm looking for a solution for a an in built sequelize error. I'm utilizing multer to process image uploads into my Amazon bucket. I got most the functionality to work, but I have a validation error, for some reason for this put function I'm running I'm getting the following error.

ValidationError [SequelizeValidationError]: string violation: previewImage cannot be an array or an object
{
  errors: [ 'previewImage cannot be an array or an object' ],
  title: 'Validation error'
}

The local database I'm using is sqlite3. I was hoping to find a solution for this error so that it will be not an issue locally as well when deployed.

Here is the relevant info for the model:

previewImage:{
    type: DataTypes.STRING
}

migration:

previewImage: {
   type: Sequelize.STRING
}

The route:

router.put('/:id', requireAuth,
    singleMulterUpload('previewImage'),
    validateAlbum, async (req, res, next) => {
        const { user } = req;
        const { id } = req.params;
        const { title, description } = req.body;
        console.log(req.file)
        const previewImage = singlePublicFileUpload(req.file);
        const album = await Album.findByPk(id);

        if (!album) {
            return next(notFoundError('Album'));
        }

        if (album.userId === user.id) {
            await album.update({
                title,
                description,
                previewImage: previewImage
            });

            res.json(album);
        } else {
            return next(forbiddenError());
        }
    });

The multer middleware:

const singlePublicFileUpload = async (file) => {
  const { originalname, mimetype, buffer } = await file;
  const path = require("path");

  const Key = new Date().getTime().toString() + path.extname(originalname);
  const uploadParams = {
    Bucket: NAME_OF_BUCKET,
    Key,
    Body: buffer,
    ACL: "public-read",
  };
  const result = await s3.upload(uploadParams).promise();

  return result.Location;
};


const singleMulterUpload = (nameOfKey) =>
  multer({ storage: storage }).single(nameOfKey);

The Frontend is react-redux based. This is the thunk that passes the data to the backend.

export const putAlbum = album => async dispatch => {
    const { id, title, description, previewImage } = album;

    const formData = new FormData();
    formData.append('title', title);
    formData.append('description', description);
    if(previewImage) formData.append('previewImage', previewImage);

    const response = await csrfFetch(`/api/albums/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        body: formData
    });

    if (response.ok) {
        const data = await response.json();
        dispatch(setAlbum(data));
        return response;
    }
}


The form that handles the file upload:


const [previewImage, setPreviewImage] = useState(album.previewImage);

const previewImageHandler = (e) => {
    const file = e.target.files[0];
    if (file) {
         setPreviewImage(file);
    }
};

const handleSubmit = (e) => {
      e.preventDefault();
      setErrors([])

      dispatch(albumActions.putAlbum({
         id: album.id,
         title,
         description,
         previewImage
      }))
         .then(() => setShowModal(false))
         .catch(async (res) => {
             const data = await res.json();
             if (data && data.errors) setErrors(data.errors);
          })
    }

The file upload:

<input
     type='file'
     onChange={previewImageHandler}
/>

This for the most part works. When I use a key value pair within the object the function passes through no problem. If there's a suggestion for a way to work around this validation error with sqlite3, I would greatly appreciate your input.

0 Answers
Related