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

Node.js中Multer上传媒体文件至MongoDB存为空数组问题求助

问题解决:form-data上传文件时MongoDB的media字段为空数组

问题根源

  • 路由中误用了multer中间件名称:你multer配置导出的是upload,但路由里写的是storage,导致multer未生效,文件没被处理
  • 文件上传后,multer将文件信息存放在req.files对象中,而非req.body.media,你当前从req.body读取media自然为空

修复步骤

1. 修正路由中间件名称

将路由中的storage替换为upload(与multer导出的中间件名一致):

router.post("/createPost", auth, upload, post.createPost);

2. 修改createPost逻辑,从req.files提取文件信息

在createPost函数中,不再从req.body获取media,而是从req.files提取文件路径/文件名,组装成需要存储的数组:

exports.createPost = async (req, res) => {
  try {
    const user = await User.findById(req.user._id);
    if (!user) return res.status(401).json({ message: "No user found" });
    // 不再从req.body取media,改为从req.files提取
    const { hashTags, postStatus } = req.body;
    // 组装media数组,存储文件的访问路径(可根据需求调整格式)
    const media = req.files.map(file => `/uploads/${file.filename}`);

    const mentions = await User.find(
      { User_name: req.body.mentions },
      { User_name: 1, _id: 0 }
    );

    if (
      req.body.mentions &&
      (!Array.isArray(mentions) || mentions.length === 0)
    ) {
      return res.status(404).send("Please enter valid user name");
    }

    let payLoad = {
      userId: req.user._id,
      media,
      hashTags,
      postStatus,
    };

    if (mentions.length > 0) {
      payLoad = { ...payLoad, mentions };
    }

    let new_post = await new Post(payLoad).save();
    return res.status(200).send(new_post);
  } catch (error) {
    return res.status(500).send(error.message);
  }
};

3. 可选:兼容无文件上传的场景

如果允许用户发布不带媒体的帖子,可添加空值判断:

const media = req.files ? req.files.map(file => `/uploads/${file.filename}`) : [];

内容的提问来源于stack exchange,提问作者Talc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:15:35