I've been trying for days to get this to work, mostly because I think getting it to work would result in the DRYest code for my application.
I have the current schema:
var TechnologySchema = new Schema({
name: { type: String, unique: true },
type: String,
attributes: Schema.Types.Mixed
});
TechnologySchema.virtual( 'iron' ).get( function() {
console.log( this );
if ( 'unit' == this.type ) {
var iron = this.attributes.armour * 100;
if ( _.contains( this.attributes.abilities, 'E' ) ) {
iron = iron / 2;
}
if ( _.contains( this.attributes.abilities, 'FA' ) ) {
iron += iron * 0.3;
}
}
return iron;
});
TechnologySchema.set( 'toJSON', { virtuals: true } );
mongoose.model( 'Technology', TechnologySchema );
Then, after fetching the technology data, I have the following:
console.log( JSON.stringify( technologies ) );
Now, based on everything I've read - JSON.stringify should be calling toJSON on my collection, which will look at the virtual attributes I have defined (as specified in the toJSON option) and do the conversion, pull in the value.etc.
What's annoying me is - the virtual attribute is never actually getting called - which means no attribute in the JSON.
Can anyone tell me what the hell is going on?! I'm sure it's something super basic I've missed =\