【问题标题】:Result of sequelize findByPksequelize findByPk 的结果
【发布时间】:2020-10-30 22:52:42
【问题描述】:

我想找一个 id 的 itme 是:1 const student = await this.db.Student.findByPk(1)

当我得到结果然后控制台它(console.log(student))

student {
  dataValues: { id: 1, name: 'Darush', family: 'Hamidi' },
  _previousDataValues: { id: 1, name: 'Darush', family: 'Hamidi' },
  _changed: Set(0) {},
  _options: {
    isNewRecord: false,
    _schema: null,
    _schemaDelimiter: '',
    raw: true,
    attributes: [ 'id', 'name', 'family' ]
  },
  isNewRecord: false
}

然后将学生发送到浏览器结果将是 (res.send(student))?

{
  "id": 1,
  "name": "Darush",
  "family": "Hamidi"
}

为什么我们有不同?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    我将rwa 设置为true:效果很好

    const student = await this.db.Student.findByPk(1,{ raw: true })
    

    【讨论】:

      【解决方案2】:

      之所以出现差异是因为使用findByPk 方法(以及所有类似方法)您会得到一个Sequelize 模型的实例而不是普通对象,并且当您将此模型实例传递给res.send 时,它会被序列化为仅具有模型属性的普通对象. 如果您希望从模型实例调用get({ plain: true }) 获取普通对象,则不会有任何区别。

      const plainStudentObj = student.get({ plain: true })
      res.send(plainStudentObj)
      

      【讨论】:

        猜你喜欢
        • 2020-03-25
        • 2019-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        相关资源
        最近更新 更多