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

Mar*_*ira 5 javascript sails.js waterline sails-mongo

这是我的 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;
        }
    }
  };
Run Code Online (Sandbox Code Playgroud)

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

<%= users.toJSON().link %> 
Run Code Online (Sandbox Code Playgroud)

有没有办法为用户创建一个属性或一些方法?喜欢:

module.exports = {

       attributes: {

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

Tra*_*ebb 2

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