How to use both 'include' and 'attributes' in 'findByPk' statement in Sequelize. This is my code:
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."
});
});;
}
But it only works when I use 1 of 2 only.
If I just use: attributes: { exclude: ['password']}
the result is as follows:
{
"data": {
"id": 1,
"username": "admin",
"email": "[email protected]",
"createdAt": "2021-09-27T04:22:56.660Z",
"updatedAt": "2021-09-27T04:22:56.660Z"
},
"resultCode": 1,
"message": ""
}
If I just use: {include: ["roles"]}
so the result is as follows
{
"data": {
"id": 1,
"username": "admin",
"email": "[email protected]",
"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": ""
}
How to use both in my code? Because I dont want to show 'password' field in my result but I want to show the roles of user in my result. How to do like that. Thanks you in advanced
CodePudding user response:
Options should be in 1 object like this.
User.findByPk(id,
{
include: ["roles"],
attributes: {
exclude: ['password']
}
})