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

86
Views
Virtual Population based on Query Type

Trying to figure out a way to populate a virtual only when the model receives a findOne command as opposed to the find command. Wrapping the virtual function inside a conditional statement does not work as it is no longer acknowledged by the schema so I'm at a loss on how to accomplish this. If you cannot use conditionals when setting virtuals, is it just not possible to create virtuals only in certain circumstances ?

Original Virtual

Schema.virtual( 'stats' , { 
    ref: 'Stat',
    foreignField: 'account',
    localField: '_id',
});

Conditional within Pre Find hook doesn't work:

Schema.pre( /^find/ , function( next ) {
    
    if ( this.op === 'findOne' ) {
        
        Schema.virtual( 'stats' , { 
            ref: 'Stat',
            foreignField: 'account',
            localField: '_id',
        });
    }
}

SOLUTION:

I found a workaround by setting a 'find_one' variable in the Pre Find hook and removing the virtual within the toJSON method if the variable returns false. I'm still hoping for a better way to achieve this but this will do if nobody has a better solution.

let find_one ;

Schema.pre( /^find/ , function( next ) {
        
        this.op === 'findOne' ? find_one = true : find_one = false ;
}

Schema.methods.toJSON = function () {

    if ( !find_one ) delete this.stats ;
    
    return data;
};
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!