Virtuals to JSON output does not appear to be working

25 views
Skip to first unread message

Kirk Bushell

unread,
Jul 21, 2013, 1:57:12 PM7/21/13
to mongoo...@googlegroups.com
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 =\

Kirk Bushell

unread,
Jul 21, 2013, 2:19:07 PM7/21/13
to mongoo...@googlegroups.com
Just want to add that I've tried using toJSON and toObject settings on the schema, both have failed. I never see the virtual attribute ('iron') and that method never gets called.

Stumped.

Kirk Bushell

unread,
Jul 21, 2013, 5:10:29 PM7/21/13
to mongoo...@googlegroups.com
So I finally got this working - and I couldn't find in the docs where this was actually mentioned - but in order to get toJSON working correctly with virtuals, it seems that both toObject and toJSON needs to be defined as part of the settings of the Schema.
Reply all
Reply to author
Forward
0 new messages