繁体   English   中英

如何在Waterline / Sails.js模型中创建“计算”字段?

[英]How to create 'calculated' fields at Waterline/Sails.js Model?

这是我的Users.model:

module.exports = {

    attributes: {

        name: {
            type: 'string',
            required: true,
            minLength: 3,
            maxLength: 30
        },

        username: {
            type: 'string',
            required: true,
        },

        toJSON: function() {
          var obj = this.toObject();
          obj.link = sails.config.globals.baseUrl + sails.config.routes.user + obj.id;
          return obj;
        }
    }
  };

我想要的是使用一些在模型中“预先”计算的属性。 我的解决方案是在toJSON()函数中注入attr,但在我必须使用的视图中:

<%= users.toJSON().link %> 

有一种方法可以为用户创建属性或某些方法吗? 喜欢:

module.exports = {

       attributes: {

        name: {
            type: 'string',
            required: true,
            minLength: 3,
            maxLength: 30
        },
        myPersonalAttribute: function(){
           return "Value"   
        }
}

您可以使用属性方法返回派生值。 请在此处查看我对您的github问题的回复: https//github.com/balderdashy/waterline/issues/626#issuecomment-54192398

module.exports = {

    attributes: {

        name: {
            type: 'string',
            required: true,
            minLength: 3,
            maxLength: 30
        },

        myPersonalAttribute: function() {
            return "Value"
        },

        toJSON: function() {
            var obj = this.toObject()
            obj.myPersonalAttribute = this.myPersonalAttribute()
            return obj
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM