自定义属性方法如何在Sails js中工作

How do Custom Attribute Methods work in Sails js

本文关键字:js 工作 Sails 方法 自定义属性      更新时间:2023-09-26

根据文档,自定义属性方法可以在模型上定义,然后在通过Waterline、Sails JS的ORM进行的查询返回的对象上使用。

这对我不起作用。我正在从查询中获取正确的数据,但我在模型上声明的函数都不起作用。尝试调用它们会导致TypeError:Object[Object Object]没有方法"methodName"

(更新为更清晰的示例)

这是我的模型与自定义属性方法

module.exports = {
attributes: {
  firstName : {
    type: 'string'
  },
  lastName : {
    type: 'string'
  }
},
  // Custom Attribute Method
  fullName : function(){
    return this.firstName + " " + this.lastName
  }
};

这是我在控制器中使用它的地方

module.exports = {
  findMe: function(req, res){
    User.findOne({firstName:'Todd'}).exec(function(err, user){
      console.log(user.fullName()); //<--TypeError: Object [object Object] has no method 'fullName'
      res.send(user);
    })
   }
};

我错过了什么?

的其余属性应包含全名

module.exports = {
    attributes: {
      firstName : {
        type: 'string'
      },
      lastName : {
        type: 'string'
      },
      fullName : function(){
        return this.firstName + " " + this.lastName
      }
    }
}