如何在 Sequelize 的“findByPk”语句中同时使用“include”和“attributes”?

Des*_*ado 3 postgresql orm node.js express sequelize.js

如何在 Sequelize 的“findByPk”语句中同时使用“include”和“attributes”。这是我的代码:

exports.findOne = (req, res) => {
  var id = req.params.id;

  User.findByPk(id, 
    
    {
      include: ["roles"] 
    }, 
    {
      attributes: {
         exclude: ['password']
      }
    }
    )
      .then(data => {
        res.send({"data": data, "resultCode": 1, "message": ""});
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving users."
        });
      });;

}
Run Code Online (Sandbox Code Playgroud)

但只有当我只使用 2 中的 1 时它才有效。如果我只使用:attributes: { exclude: ['password']}结果如下:

{
    "data": {
        "id": 1,
        "username": "admin",
        "email": "admin@gmail.com",
        "createdAt": "2021-09-27T04:22:56.660Z",
        "updatedAt": "2021-09-27T04:22:56.660Z"
    },
    "resultCode": 1,
    "message": ""
}
Run Code Online (Sandbox Code Playgroud)

如果我只是使用:{include: ["roles"]}那么结果如下

{
    "data": {
        "id": 1,
        "username": "admin",
        "email": "admin@gmail.com",
        "password": "$2a$08$m54ioIwzpZRVC9/HqkHyqezOornjmvT9pDEJcOhHbNcSmLOfw3Sg.",
        "createdAt": "2021-09-27T04:22:56.660Z",
        "updatedAt": "2021-09-27T04:22:56.660Z",
        "roles": [
            {
                "id": 2,
                "name": "moderator",
                "createdAt": "2021-09-27T04:20:46.956Z",
                "updatedAt": "2021-09-27T04:20:46.956Z",
                "user_roles": {
                    "createdAt": "2021-09-27T04:22:56.791Z",
                    "updatedAt": "2021-09-27T04:22:56.791Z",
                    "roleId": 2,
                    "userId": 1
                }
            },
            {
                "id": 3,
                "name": "admin",
                "createdAt": "2021-09-27T04:20:46.956Z",
                "updatedAt": "2021-09-27T04:20:46.956Z",
                "user_roles": {
                    "createdAt": "2021-09-27T04:22:56.791Z",
                    "updatedAt": "2021-09-27T04:22:56.791Z",
                    "roleId": 3,
                    "userId": 1
                }
            }
        ]
    },
    "resultCode": 1,
    "message": ""
}

Run Code Online (Sandbox Code Playgroud)

如何在我的代码中同时使用两者?因为我不想在结果中显示“密码”字段,但我想在结果中显示用户的角色。怎么办呢。提前谢谢你

Emm*_*mma 5

选项应该位于 1 个对象中,如下所示。

User.findByPk(id, 
{
  include: ["roles"],
  attributes: {
     exclude: ['password']
  }
})
Run Code Online (Sandbox Code Playgroud)