总结问题
我正在尝试更改 JSON 对象的某些字段,但 console.log 或 res.send 时得到的结果不是预期的
我已经尝试过的
- promise 然后
- 带有 async/await 的 Promise
- 尝试使用以下方式更改字段:
user2 = {
...user,
newFiels : 'newfiled',
}
- 尝试使用 Object.assign(...) 更改对象
- 在 VS Code 中调试:实际上显示了预期结果(仅在调试器中),但在我 console.log 时却没有显示...
显示一些代码
我正在使用 Sequelize,字段“角色”并不直接位于表“用户”上。因此,我使用 include (执行 JOIN)来获取角色:
- 查找用户
- 确定他是否是技术人员
- 根据2)将角色添加为新字段
- 将用户(现在具有正确的语法)放入response.userInfo 字段
- 发回数据
// in login function
let response = {
status: "NotOK",
userInfo: {
username: null,
nom: null,
prenom: null,
role: null,
},
infoMsg: null,
error: false,
errorMsg: null,
}
const usernameInput = req.query.username;
const passwordInput = req.query.password;
// 1)
Utilisateurs.findOne({
attributes: ['username', 'nom', 'prenom'],
include: [
{ model: Techniciens },
{ model: Magasiniers },
],
where: {
[Op.and]: [
{ username: usernameInput },
{ password: passwordInput },
],
}
})
.then(user => {
if (user) {
// 2) and 3)
if (user.technicien != null) {
user.role = 'technicien';
} else {
user.role = 'magasinier';
}
// 4)
response.userInfo = user;
response.status = 'OK'
response.infoMsg = "User found !"
console.log(`response : ${JSON.stringify(response)}`);
// 5)
res.send(response);
return;
} else {
// ...
}
})
.catch(error => {
// ...
});
除了4)之外,一切似乎都有效,但我不知道为什么
描述预期结果和实际结果
预期结果
我正在做一个项目的后端,我被要求提供这种格式的对象(请参阅响应):
Description: authenticate the user
Body content :
{
"username" : "theUsername",
"password" : "thePassword"
}
Response :
{
"status" : "OK/NotOK",
"userInfo" : {
"username" : "theUsername",
"nom" : "theName",
"prenom" : "theLastName",
"role" : "magasinier/technicien"
},
"infoMsg": "infomsg",
"error": true/false,
"errorMsg": "errmsg"
}
实际结果
{
"status":"OK",
"userInfo":{
"username":"davalres",
"nom":"Alvarez",
"prenom":"David",
"technicien":null,
"magasinier":{
"username":"davalres"
}
},
"infoMsg":"User found !",
"error":false,
"errorMsg":null
}
在“实际结果”之前我可以在调试器中看到的内容
正如你所看到的,我想要的所有字段都在这里。也许我很困惑,我不应该拥有像 __eagerlyLoadedAssociations
, ...
最佳答案
您获得的 user
对象是一个模型实例,因此我不会将此类对象嵌入到您自己的响应对象中,也不会直接修改它,因为模型最终可能会恢复您对其所做的未保存的更改。
而是通过调用 .get({plain:true})
来获取所需信息的干净副本。我个人也会将 response
的范围保留在 then
回调本地(并在需要时在 catch
回调中创建另一个):
if (user) {
let response = {
status: "OK",
userInfo: {
...user.get({plain:true}),
role: user.technicien ? 'technicien' : 'magasinier';
},
infoMsg: "User found",
error: false,
errorMsg: null,
};
console.log(`response : ${JSON.stringify(response)}`);
res.send(response);
return;
} else //....
关于node.js - 在 Promise.then 之后和 res.send 之前未按需要修改对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441613/