Ghasem Khalili
Ghasem Khalili

Reputation: 973

Result of sequelize findByPk

I want to find an itme with the id is: 1 const student = await this.db.Student.findByPk(1)

when I get the result then console it(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
}

then send the student to browser result will be (res.send(student))?

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

why we have a difference ?

Upvotes: 0

Views: 2199

Answers (2)

Ghasem Khalili
Ghasem Khalili

Reputation: 973

I set rwa to true: It works Perfectly

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

Upvotes: 6

Anatoly
Anatoly

Reputation: 22793

The difference appears because using findByPk method (and all similar ones) you get a Sequelize model's instance and not a plain object and when you pass this model instance to res.send it is serialized into plain object with model attributes only. If you wish to get a plain object from a model instance call get({ plain: true }) and then there will be no difference.

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

Upvotes: 1

Related Questions