node.js - 在 Promise.then 之后和 res.send 之前未按需要修改对象字段

标签 node.js express promise sequelize.js javascript-objects

总结问题

我正在尝试更改 JSON 对象的某些字段,但 console.log 或 res.send 时得到的结果不是预期的

我已经尝试过的

  1. promise 然后
  2. 带有 async/await 的 Promise
  3. 尝试使用以下方式更改字段:
user2 = {
    ...user,
    newFiels : 'newfiled',
}
  • 尝试使用 Object.assign(...) 更改对象
  • 在 VS Code 中调试:实际上显示了预期结果(仅在调试器中),但在我 console.log 时却没有显示...
  • 显示一些代码

    我正在使用 Sequelize,字段“角色”并不直接位于表“用户”上。因此,我使用 include (执行 JOIN)来获取角色:

    1. 查找用户
    2. 确定他是否是技术人员
    3. 根据2)将角色添加为新字段
    4. 将用户(现在具有正确的语法)放入response.userInfo 字段
    5. 发回数据
    // 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
    }
    

    在“实际结果”之前我可以在调试器中看到的内容

    debugger image 正如你所看到的,我想要的所有字段都在这里。也许我很困惑,我不应该拥有像 __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/

    相关文章:

    node.js - 我应该如何更改 NodeJS - Apache 设置才能获得所需的结果?

    node.js - Express.js、 Passport .js : why shared sessions?

    javascript - 如何遍历 div 中的 ul 元素并在提交时单独隐藏它们?

    JavaScript 原生 Promise 对两个结果执行回调

    javascript - POST 请求 - 不适用于 Node 和 Express

    node.js - 无法以只读模式插入表

    typescript - Multer 处理错误, typescript 类型有问题

    javascript - 我如何在 PDF 传单中旋转自定义标记(在网站作品中)

    javascript - Coffeescript Promise 与 Jquery Post

    javascript - node.js 需要来自父文件夹