如何在 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."
});
});;
}
但它僅在我僅使用 2 個中的 1 個時才有效。如果我只是使用:attributes: { exclude: ['password']}結果如下:
{
"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": ""
}
如果我只是使用:{include: ["roles"]}所以結果如下
{
"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": ""
}
如何在我的代碼中同時使用兩者?因為我不想在結果中顯示“密碼”欄位,但我想在結果中顯示用戶的角色。這樣的怎么辦。提前謝謝你
uj5u.com熱心網友回復:
選項應該在這樣的 1 個物件中。
User.findByPk(id,
{
include: ["roles"],
attributes: {
exclude: ['password']
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351721.html
