You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Express通过FormData向MongoDB存储字符串数组异常问题排查

解决Mongoose存储URL数组仅存入单个元素的问题

问题根源

你在创建新MongoDB文档时错误使用了MongoDB的更新操作符$push,同时未正确替换req.body中原始的JSON字符串格式的articelImages字段,导致数组仅存入单个元素(实际是把解析后的数组当成了单个元素,或者直接保留了JSON字符串)。

修正方案

1. 修复后端控制器代码

创建新文档时无需使用$push(该操作符仅用于更新已有文档),直接将解析后的数组赋值给articelImages字段即可:

export const newArticel = async (req, res) => {
  try {
    // 解析JSON字符串为数组
    const parsedImages = JSON.parse(req.body.articelImages);
    // 构造文档对象,替换原始的JSON字符串为解析后的数组
    const newArt = new Art({
      ...req.body,
      articelImages: parsedImages
    });

    const art = await newArt.save();
    res.status(200).json(art);
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: "创建文章失败" });
  }
};

2. 修复前端请求的Content-Type设置

你使用FormData发送数据,但手动设置了Content-Type: application/json,这会导致后端解析数据异常(虽然当前能拿到数据,但属于错误配置),建议移除该配置,让axios自动处理FormData的请求头:

let data = new FormData();
data.append("articelTitle", title);
data.append("articelImages", JSON.stringify(uploadImages));
data.append("artikelDescription", descEditor);
data.append("articelPrice", price);
data.append("articelConditions", condition);
try {
  axios
    .post("http://localhost:8800/api/articel/new", data)
    .then((res) => {
      console.log(res.data);
    });
} catch (error) {
  console.log(error);
}

关键说明

  • Mongoose创建新文档时,直接给数组字段赋值数组即可,$push是用于更新已有文档时向数组追加元素的操作符,创建阶段不生效。
  • 前端发送FormData时,浏览器会自动设置正确的multipart/form-data请求头,手动指定application/json会破坏FormData的解析逻辑。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:01:08