Cannot find any documentation on serializeFunctions, and getting an error about "body function must be specified."

I have a $project within my query that looks like the following:

{
    $project: {
        _id: 1,
        content: {
            $function: {
                body: function (str) {
                    if (logic) {
                        return someValue
                    } else {
                        return null
                    }
                },
                args: ["$content"],
                lang: "js"
            }
        },
    }
}

This isn’t the exact content, since I had to change variable names and logic for privacy, but you get the idea.

Initially I was getting the error MongoError: Invalid $project :: caused by :: The body function must be specified.

Upon researching this issue, I located (relevant help case ticket) and this was their response:

Currently I’m running on Mongoose 5.13.14 and my db is on 4.4.14 so I would think that this issue would’ve already been handled by now.

So, just in case I was being an idiot I was looking for documentation on this option serializeFunctions and could not find anything anywhere, not on the mongo docs nor just by simply googling the option. Can anyone link me to the documentation?

Or better yet, help me solve this error!

I tried setting the body function to a string like in his first option, as well as this user’s solution on stackoverflow, but that simply results in the error MongoError: SyntaxError: unterminated parenthetical so I’m not sure what to do.

Any help would be greatly appreciated - thanks.

Hi @Charlie_Buyas

I tried this short code for testing purposes by taking inspiration from the example you give, using Mongoose 5.13.14 and MongoDB 5.0.8:

const Test = mongoose.model('Test', {x: Number})

async function exec() {
  const doc = new Test({x: 1})
  await doc.save()

  const res = await Test.aggregate([
    {$project: {
      _id: 1,
      result: {
        $function: {
          body: function(x) {
            if (x === 1) {
              return 'Found'
            } else {
              return null
            }
          },
          args: ['$x'],
          lang: 'js'
        }
      }
    }}
  ])
  console.log(res)

  await mongoose.connection.close()
}

The output it gives:

[ { _id: 6296b9567edf52f41fde6180, result: 'Found' } ]

So it seems to behave as expected.

Could you provide a simple minimal example that is causing the issue you’re seeing?

Best regards
Kevin