Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
Call a js function() inside a pipeline using $function in mongoose/MongoDB

I need to call a function declared outside my pipeline to test some data in the query.

This is my code so far:

let requestMatcher = {
        $expr: {
          $function: {
            body: function (modelType) {
              testFunction()
              return name === 'chiller'
            },
            args: ['$name'],
            lang: 'js'
          }
        }
}

let pipeline = [{ $match: requestMatcher }, { $limit: 10 }]
const data = await Model.aggregate(pipeline)
const total = await Model.countDocuments(requestMatcher)

return res.status(200).send({
    body: {
      data,
      total
    }
})

testFunction() is just a console.log nothing fancy.

Aside from that testFunction(), everything else works in my pipeline.

When this code is run, I get "testFunction is not defined" which I know it's not defined inside mongo, but I would like to use some functions and variables to validate data while being queried

Am I doing something wrong here? Or $function isn't supposed to work like that?

Is there another way that I can achieve something similar with mongoose?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!