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

Mongodb: Unsupported conversion from array to objectId

提问人:Iman Kamali 提问时间:11/3/2023 最后编辑:KrokodilIman Kamali 更新时间:11/7/2023 访问量:49

问:

我使用$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"} ],
        }
      },
    },
  ]
}
数组 MongoDB 聚合 管道 查找

评论


答:

0赞 Bob Martin 11/3/2023 #1

我会推荐这个代码。

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

祝你好运。

1赞 Joe 11/4/2023 #2

问题出在 .{$toObjectId: "$$reserveData"}

如果集合中的任何文档不包含“reserve”字段,或者包含的“reserve”字段不是 24 个字符的十六进制字符串,则转换将失败。

您需要确保集合中的所有“保留”字段都是正确的类型,在查找阶段之前过滤掉任何不正确的类型,或者使用 $convert 代替,以便处理转换失败。$toObjectId

在您显示的错误的特定实例中,它会报告保留字段包含一个数组。

如何处理该数组值将取决于其结构和内容。