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

如何通过supplier_id向Mongoose模型的对象数组添加新数据?

解决方法

第一步:修正Mongoose模型定义

你的category_details字段定义存在错误,数组类型中直接嵌套对象字段的写法无法生效,需要明确数组元素为对象结构,修改后的模型如下:

const mongoose = require("mongoose");

const supplierProduct = new mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    supplier_id: {
      type: String,
      required: true,
    },
    category_details: {
      type: [{
        category_name: {
          type: String,
          required: true,
        },
        sub_category_name: {
          type: String,
          required: true,
        },
        Purchase_Price: {
          type: String,
          required: true,
        },
      }],
      required: true,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("supplierProduct", supplierProduct);

第二步:修正原有保存路由的笔误

原路由中datapart.save()是错误变量名,需改为定义好的supplierProduct_data:

router.post("/supplierProduct-save", async (req, res) => {
  try {
    const supplier_id = req.body.supplier_id;
    const category_details = req.body.category_details;

    const supplierProduct_data = new supplierProduct({
      _id: mongoose.Types.ObjectId(),
      supplier_id: supplier_id,
      category_details: category_details,
    });

    const savedSupplierProduct = await supplierProduct_data.save(); // 修正变量名
    res.status(200).json(savedSupplierProduct);
  } catch (err) {
    res.status(500).json(err);
  }
});

第三步:编写添加分类详情的路由

使用Mongoose的findOneAndUpdate方法,配合$push操作符向指定supplier_id的文档中追加新的分类详情对象:

router.post("/supplierProduct-add-category", async (req, res) => {
  try {
    const { supplier_id, new_category } = req.body;
    // new_category格式示例:{ category_name: "wheat", sub_category_name: "b1", Purchase_Price: "1500" }

    const updatedSupplierProduct = await supplierProduct.findOneAndUpdate(
      { supplier_id: supplier_id }, // 匹配目标供应商ID
      { $push: { category_details: new_category } }, // 向数组追加元素
      { new: true, runValidators: true } // 返回更新后的文档,同时启用字段校验
    );

    if (!updatedSupplierProduct) {
      return res.status(404).json({ message: "未找到对应供应商的产品记录" });
    }

    res.status(200).json(updatedSupplierProduct);
  } catch (err) {
    res.status(500).json(err);
  }
});

关键说明

  • $push是MongoDB原生更新操作符,专门用于向数组字段追加元素
  • new: true确保接口返回的是更新完成后的最新文档
  • runValidators: true会对新添加的数组元素执行模型中定义的校验规则,保证字段完整性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:30:44