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

Mongoose数组schema类型传入多条目仅存入一条问题排查

问题根因

你目前的代码存在两处核心问题导致只能存入1条社交媒体数据:

  • Social.findById() 方法仅支持接收单个ID参数,你传入socialId数组时,它只会提取数组第一个ID做查询,最终仅返回1条社交媒体文档
  • 你没有对传入的所有socialId做存在性校验,无法识别数组中是否包含无效ID,同时原代码还有一处笔误:用户不存在时返回的错误提示误写为Invalid theme

修复方案

修改POST接口的路由逻辑即可,修改后的完整代码如下:

router.post("/", auth, async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const theme = await Theme.findById(req.body.themeId);
  if (!theme) return res.status(400).send("Invalid theme.");

  // 批量查询所有传入的社交ID对应的文档
  const socialList = await Social.find({ _id: { $in: req.body.socialId } });
  // 校验所有传入的ID都有效
  if (socialList.length !== req.body.socialId.length) {
    return res.status(400).send("包含无效的社交媒体ID");
  }

  const user = await User.findById(req.user._id);
  if (!user) return res.status(400).send("Invalid user."); // 修正原代码的提示错误

  const qrCode = new QrCode({
    user: user,
    name: req.body.name,
    theme: theme,
    social: socialList, // 传入查询到的所有社交媒体文档数组
  });

  await qrCode.save();

  res.send(qrCode);
});

补充说明

修改后Postman请求参数不需要改动,即可正常存入所有关联的社交媒体文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 04:30:04