【问题标题】:Virtual field AND real field虚场与实场
【发布时间】:2015-08-28 23:48:27
【问题描述】:

是否可以有一个虚拟字段同时也是模型中的一个字段?

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, '');
});

如果设置了 slug,我想退回 slug。如果没有,我想从 name 返回一个计算值。

我不想使用静态方法,它需要在拉取记录时成为结果的一部分。

【问题讨论】:

    标签: mongodb mongoose keystonejs


    【解决方案1】:

    您可以创建自定义 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, '');
                }
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多