在for循环中修改对象(异步/等待)

时间:2019-04-02 12:01:42

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

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)
  }
}

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

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

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

来自我的终端https://pastebin.com/w7c50YRt

的Node.js日志

2 个答案:

答案 0 :(得分:3)

猫鼬欺骗了你。它将toString()toString方法添加到文档中,仅显示模型中定义的属性。如果将其记录到控制台,则将调用toJSON(),如果将其作为json发送,则将调用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());

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

validate_<field_name>

答案 1 :(得分:1)

猫鼬根据用户模式的定义进行操作。 您应该在用户的架构中添加蓝图和图像键

相关问题