Search code examples
sequelize.jsfeathersjs

Serializing sequelize nested model


I'm using feathers + sequlize + postgres after setting everything up I have 2 models category and categories descriptions and trying to create a relationship between them, it looks like this:

Categories model

 const categories = sequelizeClient.define('categories', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    }
 }, {
    hooks: {
      beforeCount(options) {
        Object.assign(options, { raw: true });
      },
    },
})
 categories.associate = (models) => {
    categories.hasOne(models.category_description, {
      as: 'description',
      foreignKey: 'category_id',
    });
  };

Category description model

  const categoryDescription = sequelizeClient.define('category_description', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    category_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    language_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: true,
    },
  }, {
    hooks: {
      beforeCount(options) {
        Object.assign(options, { raw: true });
      },
    },
  });

  categoryDescription.associate = (models) => {
    categoryDescription.belongsTo(models.categories, {
      foreignKey: 'category_id',
    });

In find/get hook I have next code

function (context) {
    context.params.sequelize = {
      include: [{
        model: context.app.service('category-description').Model,
        as: 'description',
        attributes: ['name'],
        where: { language_id: 2 },
      }],
    };
    return Promise.resolve(context);
  },

It works perfectly aside from one little issue, when I'm trying to query categories "description" field is populated in "dot notation"

{
  description.name : 'Name'
}

and my expectation is to have an object

{
  description: {name: 'Name' }
}

It should be one line fix, but unfortunately I'm not able to figure it out


Solution

  • Whoever faced same issues, the solution is very easy, you just need to add a boolean flag

    raw: false,

    in your feather's service