我只想显示一张产品图片

时间:2021-01-06 06:29:38

标签: node.js mongodb api mongoose

这是节点js中的代码

const result = await OrderDB.aggregate([
      { $match: { _id: mongoose.Types.ObjectId(id) } },
      {
        $lookup: {
          from: 'products',
          localField: 'product',
          foreignField: '_id',
          as: 'productDetail',
        },
      },
      {
        $project: {
         
          productDetail: {
            name: 1,
            price: 1,
            productImage: 1,
          },
        },
      },
    ])

这是代码的响应

{
    "message": "Get Order Successfully",
    "result": [
        {
            "_id": "5ff47348db5f5917f81871aa",
            "productDetail": [
                {
                    "name": "Camera",
                    "productImage": [
                        {
                            "_id": "5fe9b8a26720f728b814e246",
                            "img": "uploads\\product\\7Rq1v-app-7.jpg"
                        },
                        {
                            "_id": "5fe9b8a26720f728b814e247",
                            "img": "uploads\\product\\FRuVb-app-8.jpg"
                        }
                    ],
                    "price": 550
                }
            ]
        }
    ]
}

我只想从使用 nodejs 和 mongoose 的响应中显示一个 productImage

<块引用>

这是在聚合投影中使用

<块引用>

我正在使用 $arrayElemAt 但它不起作用

<块引用>

我也使用 $first 但它不起作用

<块引用>

所以我使用的投影方法只显示一个 *productImage*

2 个答案:

答案 0 :(得分:1)

数据看起来像多级嵌套。

你有array of results, each result contains array of productDetails

play

您需要展开数据以获得第一个productImage

db.collection.aggregate([
  {
    "$unwind": "$result"
  },
  {
    "$unwind": "$result.productDetail"
  },
  {
    $project: {
      pImage: {
        "$first": "$result.productDetail.productImage"
      }
    }
  }
])

答案 1 :(得分:0)

有了上面的回复

db.collection.aggregate([
  {
    "$project": {
      productDetails: {
        $map: {
          input: "$productDetail",
          in: {
            "$mergeObjects": [
              "$$this",
              {
                productImage: {
                  "$arrayElemAt": [
                    "$$this.productImage",
                    0
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

工作Mongo playground