Add arguments in a virtual getter

蓝咒 提交于 2019-12-23 16:43:48

问题


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 ?


回答1:


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]
    }
};



回答2:


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" );


来源:https://stackoverflow.com/questions/13566817/add-arguments-in-a-virtual-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!