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

Mongoose创建Categories子文档追加到Event父文档id为空问题咨询

问题原因
  • 核心诱因:调用Category.create()批量传入分类数组创建文档时,回调函数的第二个返回值为新创建的所有分类文档组成的数组,而非单个文档对象。你的代码直接读取category._id,等价于读取数组的_id属性,该属性不存在所以返回undefined,对应Mongoose调试日志中写入的空值。
  • 逻辑缺陷:当前写法仅尝试写入1个分类ID,就算取值正确也无法满足批量创建多个分类的存储需求。
  • 语法混用问题:外层函数已经用async声明、由catchAsync做异步错误捕获,内层依然使用回调嵌套写法,既浪费了现有封装能力,也提升了逻辑出错概率。
修复方案

方案1:适配原有回调逻辑

修改Category.create回调内的取值逻辑,批量提取所有分类ID后存入Event文档:

exports.addCategories = catchAsync(async (req, res, next) => {
  const categories = req.body;
  const eventID = categories.pop().eventId;

  Event.findOne({ _id: eventID }, (err, event) => {
    if (err) return res.status(400).send(err);
    if (!event) return res.status(400).send(new Error("Could not find that event"));

    Category.create(categories, (err, newCategories) => {
      if (err) return res.status(400).send(err);
      // 批量提取所有新分类的ID写入数组
      const categoryIds = newCategories.map(item => item._id);
      event.categories.push(...categoryIds);
      event.save((err) => {
        if (err) return res.status(400).send(err);
        res.status(200).json(newCategories);
      });
    });
  });
});

方案2(推荐):改用async/await写法,移除回调嵌套

和外层异步封装适配,代码更简洁易维护:

exports.addCategories = catchAsync(async (req, res, next) => {
  const categories = req.body;
  const eventID = categories.pop().eventId;
  // 校验Event是否存在
  const event = await Event.findById(eventID);
  if (!event) return res.status(400).send(new Error("Could not find that event"));
  // 批量创建分类
  const newCategories = await Category.create(categories);
  // 提取所有分类ID存入Event
  event.categories.push(...newCategories.map(item => item._id));
  await event.save();
  res.status(200).json(newCategories);
});

附加校验:请确认你的Event模型中categories字段定义为type: [mongoose.Schema.Types.ObjectId], ref: 'Category',避免字段类型不匹配导致的后续查询问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:27:04