Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Failed to parse objectId '' in $convert with no onError value: Invalid string length for parsing to OID, expected 24 but found 0

I am creating an aggregate query, but I'm running into an issue with some of my fields that need to be converted to ObjectIDs'. There are certain documents that do not have anything in the fields(null, ''), so I want to ignore those cases.

{
   "$project": {
    "Company": {
        "$toObjectId": "$Company"
    },
    "Lease": {
        "$toObjectId": "$Lease"
    },
    "Well": {
        "$toObjectId": "$Well"
   }
}

I've tried something similar to this:

{$ifNull: [{ $toObjectId: "$Company" }, ''] }

But I'm still receiving the error.

What is the best way to fix this?

like image 486
Stephen Romero Avatar asked Dec 31 '22 19:12

Stephen Romero


1 Answers

I realized I was using the short syntax of $toObjectId, which didn't have the options of onNull, or onError.

I needed to revert back to $convert:

{$convert: {input: '$Company', to : 'objectId', onError: '',onNull: ''}}

Source

like image 114
Stephen Romero Avatar answered Jan 02 '23 08:01

Stephen Romero