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
最佳答案
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());
关于javascript - 在 for 循环中修改对象(异步/等待),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55474305/