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

如何修改Mongoose订单Schema以支持MongoDB多菜品单次下单

订单管理系统Mongoose Schema修改方案

要实现同一客户通过单个POST请求订购多种菜品的功能,只需要把原Schema中的单菜品字段调整为菜品数组,让一个订单可以关联多个菜品。以下是修改后的完整Schema:

const OrderSchema = new Schema({
    cusName: {
        type: String,
        required: [true, '必须提供客户名称'],
        trim: true,
        maxlength: [20, '客户名称不能超过20个字符']
    },
    // 新增菜品数组,存储多个菜品信息
    foodItems: [
        {
            foodName: {
                type: String,
                required: [true, '必须提供菜品名称'],
                trim: true,
                maxlength: [20, '菜品名称不能超过20个字符']
            },
            quantity: {
                type: Number,
                required: [true, '必须提供菜品数量'],
                min: [1, '数量不能小于1'] // 可选:增加数量最小值限制
            }
        }
    ],
    orderTime: {
        type: Number,
        required: [true, '必须提供下单时间'],
        trim: true,
    }
});

修改说明:

  • 保留了订单级别的cusName和orderTime字段,作为整个订单的基础信息
  • 用foodItems数组替代原有的foodName和quantity字段,每个数组元素对应一个菜品的名称和数量
  • 修正了原Schema中的拼写错误:quntity改为quantity,同时统一修正了各字段的必填提示文本(原提示均为"must provide name",现在改为对应字段的中文提示)
  • 可选:给quantity增加了min:1的限制,避免出现0或负数的数量

示例POST请求体:

当客户需要订购2份Fried-rice和1份pizza时,请求数据可以这样传:

{
  "cusName": "客户1",
  "orderTime": 1720000000000,
  "foodItems": [
    {
      "foodName": "Fried-rice",
      "quantity": 2
    },
    {
      "foodName": "pizza",
      "quantity": 1
    }
  ]
}

内容的提问来源于stack exchange,提问作者Sandeepa de silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:10:19