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.
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
}