Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance impact to using virtual getters in Mongoose with Node.js?

I'm starting to make use of virtual getter methods in Mongoose in a real-world application and am wondering if there is a performance impact to using them that would be good to know about up-front.

For example:

var User = new Schema({
  name: {
    first: String,
    last: String
  }
});

User.virtual('name.full').get(function () {
  return this.name.first + ' ' + this.name.last;
});

Basically, I don't understand yet how the getters are generated into the Objects Mongoose uses, and whether the values are populated on object initialisation or on demand.

__defineGetter__ can be used to map a property to a method in Javascript but this does not appear to be used by Mongoose for virtual getters (based on a quick search of the code).

An alternative would be to populate each virtual path on initialisation, which would mean that for 100 users in the example above, the method to join the first and last names is called 100 times.

(I'm using a simplified example, the getters can be much more complex)

Inspecting the raw objects themselves (e.g. using console.dir) is a bit misleading because internal methods are used by Mongoose to handle translating objects to 'plain' objects or to JSON, which by default don't include the getters.

If anyone can shed light how this works, and whether lots of getters may become an issue at scale, I'd appreciate it.

like image 310
Jed Watson Avatar asked Nov 04 '22 10:11

Jed Watson


1 Answers

They're probably done using the standard way:

Object.defineProperty(someInstance, propertyName, {get: yourGetter});

... meaning "not on initialization". Reading the virtual properties on initialization would defeat the point of virtual properties, I'd think.

like image 167
Ry- Avatar answered Nov 11 '22 05:11

Ry-