Mongodb:不支持从数组到 objectId 的转换

问题描述 投票:0回答:1

我使用 $lookup 来加入连接 正常情况下是没有问题的。但使用管道后,程序给出错误:“Unsupported conversion from array to objectId in $convert with no onError value”

{
            $lookup:
                {
                     from: "reserves",
                 localField: "reserve",
                foreignField: "_id",
                as: "reserve",
}

此代码有效

和结果

{
    "status": "success",
    "message": "okkkk",
    "results": 1,
    "data": [
        {
            "_id": "sdfgsd56",
            "customer": "fghdfbv",
            "price": 170000,
            "off": 30000,

            "reserve": [
                {
                    "_id": "65421d801c128f2ed899a7a4",
                    "customer": "6540debf6ca6663eb886eb46",
                    "service": "65421c961c128f2ed899a631",
                    "__v": 0
                }
            ]
        }
    ]
}

但是由于我们使用管道,我必须更改代码如下,然后出现错误

{
            $lookup:
                {
                   from: "reserves",
                   'let': { reserveData: "$reserve" },
                   as: "reserve",
                    pipeline: [
                        {
                        $match: {
                            $expr: {
                                $eq: ["$_id",  {$toObjectId: "$$reserveData"} ],
                            }
                        },
                    },
]
}
arrays mongodb aggregate pipeline lookup
1个回答
0
投票

我推荐这个代码。

{
  $lookup: {
    from: "reserves",
    let: {
      reserveData: "$reserve"
    },
    pipeline: [{
      $match: {
        $expr: {
          $eq: ["$$reserveData", "$_id"],
        }
      },
    }, ],
    as: "reserve"
  }

祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.