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

5
这是我的用户模型 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()函数中注入属性,但在视图中我必须使用:
<%= users.toJSON().link %> 

有没有办法为用户创建属性或某些方法?比如:
module.exports = {

       attributes: {

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

1
你最后一个关于myPersonalAttribute的示例应该可以正常工作(除了缺少})。 你试过了吗? - sgress454
我尝试了,在代码中放置了“}”,但是没有起作用。报错说我的“myPers...” 方法不存在。 - Marcelo Boeira
2个回答

2

1
我同意这是正确的,但这不是OP说他们已经在做的事情吗?为什么还是不起作用呢? - sgress454

0
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
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接