Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda