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

Mongoose:如何筛选多文档中子文档并返回含父信息的普通数组

电商变体数据筛选与结构转换问题

我开发了一款电商应用,其中产品(Product)包含多个变体(variant),变体存储在每个Product对象的数组中,原始数据结构如下:

[
    {
      "title": "Test",
      "description": "test description",
      "variants": [
        {
           "id": 1,
           "color": "red",
           "size": "L",
           "price": 500
        },
        {
           "id": 2,
           "color": "red",
           "size": "M",
           "price": 500
        },
        {
           "id": 3,
           "color": "red",
           "size": "S",
           "price": 500
        }    
      ]
    }
]

请问能否通过变体ID进行筛选,返回忽略父产品来源但包含父产品详情的普通变体数组?目标数据结构如下:

[
        {
           "id": 1,
           "color": "red",
           "size": "L",
           "price": 500,
           "parent": {
             "title": "Test",
             "description": "test description"
           }
        },
        {
           "id": 2,
           "color": "red",
           "size": "M",
           "price": 500,
           "parent": {
             "title": "Test",
             "description": "test description"
           }
        },
        {
           "id": 3,
           "color": "red",
           "size": "S",
           "price": 500,
           "parent": {
             "title": "Test",
             "description": "test description"
           }
        },
        {
           "id": 4,
           "color": "orange",
           "size": "S",
           "price": 500,
           "parent": {
             "title": "Test 2",
             "description": "test description 2"
           }
        }  
] 

当然可以实现,以下是具体的实现思路和代码示例:

核心步骤

  1. 遍历所有产品,将每个产品的变体展开,同时为每个变体添加包含父产品关键信息的parent字段,形成全量变体数组
  2. 根据目标变体ID列表,从全量数组中筛选出匹配的变体

JavaScript实现示例

// 模拟原始产品数据
const products = [
  {
    title: "Test",
    description: "test description",
    variants: [
      { id: 1, color: "red", size: "L", price: 500 },
      { id: 2, color: "red", size: "M", price: 500 },
      { id: 3, color: "red", size: "S", price: 500 }
    ]
  },
  {
    title: "Test 2",
    description: "test description 2",
    variants: [
      { id: 4, color: "orange", size: "S", price: 500 }
    ]
  }
];

// 需要筛选的目标变体ID
const targetIds = [2, 4];

// 生成带父产品信息的全量变体数组
const allVariantsWithParent = products.flatMap(product => {
  const parentData = {
    title: product.title,
    description: product.description
    // 可根据业务需求添加更多父产品字段,如id、分类等
  };
  return product.variants.map(variant => ({ ...variant, parent: parentData }));
});

// 根据ID筛选目标变体
const result = allVariantsWithParent.filter(variant => targetIds.includes(variant.id));

console.log(result);

注意事项

  • 可根据实际业务需求调整parent字段中包含的父产品信息,避免冗余数据
  • 如果变体数量极大,可在遍历过程中直接完成筛选,减少内存占用
  • 若使用TypeScript,可定义对应的接口规范数据结构,提升代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:39:34