Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda