node.jstypescriptdatabasesequelize.jssequelize-typescript

How to change sequelize property name after join


I have an issue in sequelize orm. The data return after join has an object nested:

{
    "id": 1,
    "username": "duongdoican@gmail.com",
    "password": "$2a$12$OQHHb/D9JAs6tyclVzPWMeSVkbcR2tSmmMq9VHaqnWm3C/UKPYyNm",
    "role": {
        "name": "admin"
    }
}

I expect the result to be:

{
    "id": 1,
    "username": "duongdoican@gmail.com",
    "password": "$2a$12$OQHHb/D9JAs6tyclVzPWMeSVkbcR2tSmmMq9VHaqnWm3C/UKPYyNm",
    "role": "admin"
}

Because I join only 1 field from role table to user table so I want to change name like that, but I don't know how. Here is my code:

User.findAll({
        include: [
          {
            model: Role,
            attributes: ["name"],
            required: true
          },
        ],
        plain: true,
      });

});

Someone help me, please!


Solution

  • Try the following as an alias:

    User.findAll({
      attributes: ["id", "username", "password", [Sequelize.col("roles.name"), "role"]],
      include: [
        {
          model: Role,
          as: 'roles', // alias, define in your model (if not defined)
          attributes: [],
          required: true
        }
      ]
    });