我想做的是这样的事情:
Schema
.virtual('getSomething')
.get(function(what) {
if (!what) {
return this.somethingElse
} else {
return this.something[what]
}
})
问题是我们无法在虚拟getter中传递参数,如何在不重复代码的情况下实现类似的东西呢?
答案 0 :(得分:7)
将其添加为instance method而非虚拟吸气剂。
schema.methods.getSomething = function(what) {
if (!what) {
return this.somethingElse
} else {
return this.something[what]
}
};
答案 1 :(得分:4)
Getters不接受任何参数,因为它们应该替换正常的“get属性”功能,而不用括号。所以你需要的是定义一个方法:
Schema.methods.getSomething = function(what) {
if (!what) {
return this.somethingElse;
} else {
return this.something[what];
}
};
然后你可以简单地打电话:
mySchemaObject.getSomething( "test" );