【问题标题】:Mongoose Schema Error: "Cast to string failed for value"Mongoose 架构错误:“转换为字符串的值失败”
【发布时间】:2021-12-13 12:20:52
【问题描述】:

大家好,当我尝试使用 Mongoose Schema 发送字符串数组时出现错误 它适用于标签而不适用于 selectedFile..

Mongoose 架构:

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 });
  };

对于测试,我输入了 ["imgArr"] 的 dammy 值 我得到了这个错误 消息:“PostMessage 验证失败:selectedFile:在路径“selectedFile”处为值“['imgArr']”(类型数组)转换为字符串失败”

我能做什么? 记住标签的工作,他接受字符串数组

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我找到了解决办法

    JSON.stringify (imgArr)
    

    解决了我的问题

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 2020-12-16
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2016-01-02
      • 2017-01-21
      • 2018-11-06
      相关资源
      最近更新 更多