【问题标题】:How to project after lookup without the 'as' field mongoose如何在没有“as”字段猫鼬的情况下进行查找后投影
【发布时间】:2021-10-22 20:48:15
【问题描述】:

我有以下代码:

     const products: ReadonlyArray<Pick<IProduct, 'id' | 'gender' | 'category' | 'title' | 'description' | 'price' | 'imageFileName'>> = await UserDB.aggregate<
        Pick<IProduct, 'id' | 'gender' | 'category' | 'title' | 'description' | 'price' | 'imageFileName'>>([
          {
            $match: { _id: mongoose.Types.ObjectId(req.userId) },
          },
          {
            $lookup: {
              from: 'products',
              localField: 'inBagProducts',
              foreignField: '_id',
              as: 'product',
            },
          },
          {
            $unwind: '$product',
          },
          {
            $project: { 
              product: {
                'product.category': 1,
                'product.gender': 1,
                'product.title': 1,
                'product.description': 1,
                'product.price': 1,
                'product.imageFileName': 1,
              }
            },
          },
        ]);

这段代码给出了这样的结果:

    {
        _id: 611e2febb863ce74ac448220,
        product: {
          category: 1,
          gender: 2,
          title: 'jdwoeid',
          description: 'jfwoeifjweoi',
          price: 23902,
          imageFileName: '1628808613195-7886.png'
        }
      },
      {
        _id: 611e2febb863ce74ac448220,
        product: {
          category: 5,
          gender: 1,
          title: 'sivdosi',
          description: 'oisbdvoi',
          price: 2394,
          imageFileName: 'http://localhost:3000/images/1628875244435-3564.png'
        }
      }

预期结果是这样的:

      {
        _id: 611e2febb863ce74ac448220,
          category: 1,
          gender: 2,
          title: 'jdwoeid',
          description: 'jfwoeifjweoi',
          price: 23902,
          imageFileName: '1628808613195-7886.png'
      },
      {
        _id: 611e2febb863ce74ac448220,
          category: 5,
          gender: 1,
          title: 'sivdosi',
          description: 'oisbdvoi',
          price: 2394,
          imageFileName: 'http://localhost:3000/images/1628875244435-3564.png'
      }

没有product: {}我怎么能得到结果

【问题讨论】:

    标签: javascript typescript mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以使用$addFields 管道将_id 添加到product 属性,然后您可以使用$replaceRoot 管道。您可以将这些聚合阶段添加到您的代码中:

    [
      {
        "$addFields": {
          "product._id": "$_id"
        }
      },
      {
        "$replaceRoot": {
          "newRoot": "$product"
        }
      }
    ]
    

    下面是工作示例:https://mongoplayground.net/p/VVxXgDYFANI

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2016-10-13
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多