thinky icon indicating copy to clipboard operation
thinky copied to clipboard

Transparent getter/setter for virtual fields

Open Prinzhorn opened this issue 9 years ago • 2 comments

I've used Mongoose a ton in the past and I'm just reading through the thinky docs. First of all thank you very much for creating thinky.

I was reading about virtuals and wondered if there's a reason you didn't choose the Mongoose way. In Mongoose you don't need to call generateVirtualFields and the define doesn't need to be set using a function call. Both of these are transparently done using getters/setters on the object.

Here's a simple example

var doc = {
    firstName: 'Jane',
    lastName: 'Doe'
};

Object.defineProperty(doc, 'fullName', {
    get: function() {
        return this.firstName + ' ' + this.lastName;
    },
    set: function(value) {
        var split = value.split(' ');

        this.firstName = split[0];
        this.lastName = split[0];
    }
});

console.log(doc.fullName);

doc.fullName = 'Foo Bar';

console.log(doc.firstName, doc.lastName);

Prinzhorn avatar Feb 09 '16 09:02 Prinzhorn

I don't remember exactly why. Maybe because nested fields are not supported?

neumino avatar Feb 09 '16 15:02 neumino

Good point. Maybe Mongoose is using Proxies then to make it work with nested properties https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy . They definitely do it some way or another.

Prinzhorn avatar Feb 09 '16 16:02 Prinzhorn