Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add arguments in a virtual getter

What I'm trying to do is something like that :

Schema
.virtual('getSomething')
.get(function(what) {
    if (!what) {
        return this.somethingElse
    } else {
        return this.something[what]
    }
})

The problem is that we can't pass arguments in a virtual getter, how can I achieve something like that without having to duplicate my code ?

like image 727
Calvein Avatar asked Dec 11 '22 20:12

Calvein


2 Answers

Add it as an instance method instead of a virtual getter.

schema.methods.getSomething = function(what) {
    if (!what) {
        return this.somethingElse
    } else {
        return this.something[what]
    }
};
like image 77
JohnnyHK Avatar answered Jan 10 '23 19:01

JohnnyHK


Getters don't accept any arguments, because they are supposed to replace normal "get attribute" functionality, without brackets. So what you are need is to define a method:

Schema.methods.getSomething = function(what) {
    if (!what) {
        return this.somethingElse;
    } else {
        return this.something[what];
    }
};

and then you can simply call:

mySchemaObject.getSomething( "test" );
like image 37
freakish Avatar answered Jan 10 '23 17:01

freakish