如何在mongoosejs中设置虚函数?

时间:2016-07-04 04:28:57

标签: mongoose

例如,

var schema_t = new mongoose.Schema({
  sex: { type: String, enum: ['male', 'female'] },
})

schema_t.virtualFunction.isMale = function() {
  return this.sex === 'male';
}

// then I can use like this:
var a = new schema_t;
if(a.isMale()) {}
// instead of this
if(a.sex === 'male') {}

如何定义isMale()函数

1 个答案:

答案 0 :(得分:0)

您不需要将isMale()定义为函数,而是将其定义为虚拟属性。

var schema_t = new mongoose.Schema({
 sex: { type: String, 
 enum: ['male', 'female'] 
 },
})

schema_t.virtual('isMale').get(function(){
if(this.sex === 'male') 
 return true;
else
 return false;
}


var a = new schema_t{
        sex:'male'
        };
if(a.isMale) {
 //code 
 }

阅读更多:HERE