3

The hasMany association should return a list of object, rights? I have a user record and a few connections records connected to it.

model connections:

userId: {
      field: 'user_id',
      type: DataTypes.STRING,
      allowNull: false
    }

model users:

(users as any).associate = function associate(models: any) {
    models.users.hasMany(models.connections, {
      as: 'connections',
      foreignKey: 'user_id'
    });
  };

I include the connections model by adding it to the sequelize query params:

include: [{ model: context.app.service('connections').Model, as: 'connections' }],

The end result is that the connections property in the user response is a single object instead of an array of objects. I logged the Sequelize’s query executions and tried directly in the DB the raw query that Sequelize does for this particular call and it returns a list of records, as it should. But when I query it through the API, it returns just a single object instead of an array.

Milkncookiez
  • 6,817
  • 10
  • 57
  • 96

2 Answers2

0

Turns out the query from Sequelize needs to be marked as raw. So, in the sequelize object, you gotta include the raw: true param. This will, unfortunately, result in returning a Sequelize native object (the one that has the defaultValues prop). You can get it serialized into a normal JavaScript object by calling .get() on the result from Sequelize.

So, to sum up, you gotta add raw: true on the same level as the include prop, like so:

{
  include: [{ model: ...],
  raw: true 
}
Milkncookiez
  • 6,817
  • 10
  • 57
  • 96
0

Fixed:

.findAll({
   raw : false // <===
})

Documentation: https://sequelize.org/master/manual/raw-queries.html

// Only Set this to true if you don't have a model definition for your query.
raw: false,
Amr Ibrahim
  • 2,066
  • 2
  • 23
  • 47