2015-08-28 134 views
0

是否有可能有一個虛擬領域也是模型中的領域?虛擬領域和實際領域

var exampleSchema = new Schema({ 
     name : {type: String, required: true} 
     slug:: {type: String} 
}); 


exampleSchema.virtual('slug').get(function() { 

    if(this.slug && this.slug.length){ 
     return this.slug; 
    } 

    return this.name.toLowerCase().replace(/ /g, ''); 
}); 

如果設置了slu I,我想返回slu。。如果不是,我想從名字返回一個計算值。

我不想使用靜態方法,它需要拉動記錄時結果的一部分。

回答

0

您可以創建一個自定義getter函數,並在該值存在的情況下返回該值,否則返回該值。

var exampleSchema = new Schema({ 
    name: {type: String, required: true} 
    slug: { 
     type: String, 
     get: function(value) { 
      if (value) { 
       return value; 
      } else { 
       return this.name.toLowerCase().replace(/ /g, ''); 
      } 
     } 
    } 
});