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;
};