Sequelize-在普通对象中包含getter返回

时间:2019-03-08 13:08:29

标签: node.js sequelize.js

我有一个Sequelize类,其中定义了一些虚拟字段,如下所示:

class Post extend Sequelize.Model {
  get age () {
    return duration(this.get('createdAt'), new Date()).days
  }
}

(为简便起见,我已跳过了实际的数据库字段)

我正在运行Express应用,我希望将这些虚拟字段发送到客户端。当我调用post.get({ plain: true })时,仅传递“真实” DB字段。我得到这样的东西:

{"createdAt": "2019-03-05T09:16:50.391Z"}

使响应更像这样的最佳方法是什么?

{"createdAt": "2019-03-07T09:16:50.391Z", "age": 3}

2 个答案:

答案 0 :(得分:1)

是否有理由扩展Model?使用getterMethods属性似乎可以满足您的要求。例如:

sequelizeDB.define('my_printer_table',
  {
    printer_code    : {type: Sequelize.STRING,primaryKey: true},
    printer_name    : Sequelize.STRING
  },
  {
  getterMethods: {
    description() {
      return this.printer_code + ' ' + this.printer_name
    }
  }
});

然后,printer.get()结果为:

Object {description: "ABC ABC Printing", printer_code: "ABC", printer_name: "ABC Printing"}

答案 1 :(得分:0)

我最终使用的解决方案是在选项中显式声明getter,类似于KenOn10的建议,但使用ES6语法。这是完成的解决方案:

class Post extend Sequelize.Model {

  static init (sequelize) {
    return super.init(
      'age': {
        type: Sequelize.VIRTUAL,
        get: function () { return this.getAge() }
      }
    }, { sequelize }
  }

  getAge () {
    return duration(this.get('createdAt'), new Date()).days
  }
}

需要注意的几件事:

  • 我已将getter函数更改为名为getAge()的普通函数,因为在架构中设置get属性也会将其创建为getter。因此,如果您在该函数中调用getter,它将进入递归循环并填满堆栈。
  • get选项需要定义为完整功能,因为箭头函数没有自己的this上下文。