skip to Main Content

I used a $lookup to join a connection
There was no problem under normal circumstances. But after using pipeline, the program gives an error :"Unsupported conversion from array to objectId in $convert with no onError value"

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

This code worked

and the result

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

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

But since we use pipeline, I have to change the code as below and I get an error

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

2

Answers


  1. I’d recommend this code.

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

    Good luck.

    Login or Signup to reply.
  2. The problem is with {$toObjectId: "$$reserveData"}.

    If any document in the collection either doesn’t contain a ‘reserve’ field or contains a ‘reserve’ field that is anything other than a 24-character hex string, the conversion will fail.

    You will need to either ensure that all of the ‘reserve’ fields in the collection are the correct type, filter out any that are not the correct type before the lookup stage, or use $conver instead of $toObjectId so that you can handle the conversion failure.

    In the specific instance of the error, that you show it reports the reserve field contain an array.

    How to handle that array value will depend on its structure and content.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search