【问题标题】:Modify object in for loop (async/await)在 for 循环中修改对象(异步/等待)
【发布时间】:2019-08-23 18:02:43
【问题描述】:
exports.allUsers = async (req, res, next) => {
  try {
    let users = await User.find({})

    console.log(users)
    // [{ role: 'user',
    //   skills: [...],
    //   email: 'first.last@mail.com',
    //   education: [],
    //   createdAt: 2019-04-02T11:17:33.979Z
    // },
    // { role: 'admin',
    //   skills: [...],
    //   email: 'first.lastname@mail.com',
    //   education: [],
    //   createdAt: 2019-04-02T11:17:33.979Z
    // } ]

    for (let i = 0; i < users.length; i++) {
      users[i].bluepages = await bluepagesApi.bluepagesMail(users[i].email)
      users[i].image = await bluepagesApi.profileimage(users[i].email)

      console.log(users[i].bluepages)
      // { 
      //   job: 'Developer',
      //   givenname: 'Tony',
      //   ismanager: 'N',
      //   employeetype: 'P'
      // }
      // { 
      //   job: 'Job Title',
      //   givenname: 'Max',
      //   ismanager: 'N',
      //   employeetype: 'P'
      // }
    }

    console.log(users)
    // [{ role: 'user',
    //   skills: [...],
    //   email: 'first.last@mail.com',
    //   education: [],
    //   createdAt: 2019-04-02T11:17:33.979Z
    // },
    // { role: 'admin',
    //   skills: [...],
    //   email: 'first.lastname@mail.com',
    //   education: [],
    //   createdAt: 2019-04-02T11:17:33.979Z
    // } ]

    return res.json({
      users: users
    })
  } catch (error) {
    next(error)
  }
}

如果我在for-loop 中执行console.log(users[i].bluepages),则会显示通过 API 获取的数据,但如果我在 for-loop 中执行console.log(users[i]),则不会显示新对象。

在我的for-loop 之外/之后,这些更改也不可见。

我也尝试使用Array.map 来做,但没有成功。

来自我的终端的 Node.js 日志:https://pastebin.com/w7c50YRt

【问题讨论】:

  • 这两种方法真的返回承诺吗?另外你如何登录?您能否显示带有日志及其输出的代码?
  • 是的,他们这样做了@JonasWilms
  • 我在我的问题@JonasWilms 中添加了所有控制台日志和返回的数据
  • for-loop 正确执行,循环结束后发送 json。
  • 你能把 i 的值和数据一起打印出来吗?尝试使用 for...of 循环。

标签: javascript arrays object for-loop async-await


【解决方案1】:

mongoose 根据用户模式的定义行事。 您应该将蓝页和图像键添加到用户架构中

【讨论】:

    【解决方案2】:

    Mongoose 欺骗了你。它将toJSON()toString() 方法添加到文档中,仅显示模型中定义的属性。如果将其记录到控制台,将调用toString,如果将其发送为json,则将调用toJSON()

    console.log(
      users[0], // looks as if bluepages does not exist
      users[0].bluepages // but it does actually
    );
    

    要让用户表现得像对象,请将它们映射到常规对象:

    let users = (await User.find({})).map(u => u.toObject());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2021-10-18
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 2021-03-15
      相关资源
      最近更新 更多