Reputation: 5611
exports.allUsers = async (req, res, next) => {
try {
let users = await User.find({})
console.log(users)
// [{ role: 'user',
// skills: [...],
// email: '[email protected]',
// education: [],
// createdAt: 2019-04-02T11:17:33.979Z
// },
// { role: 'admin',
// skills: [...],
// email: '[email protected]',
// 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: '[email protected]',
// education: [],
// createdAt: 2019-04-02T11:17:33.979Z
// },
// { role: 'admin',
// skills: [...],
// email: '[email protected]',
// education: [],
// createdAt: 2019-04-02T11:17:33.979Z
// } ]
return res.json({
users: users
})
} catch (error) {
next(error)
}
}
If I do a console.log(users[i].bluepages)
inside my for-loop
the data that is fetched via an API is shown but if I do a console.log(users[i])
in my for-loop
the new object is not shown.
Also outside/after my for-loop
the changes are not visible.
I also tried to do it with Array.map
without any success.
Node.js logs from my terminal: https://pastebin.com/w7c50YRt
Upvotes: 1
Views: 364
Reputation: 99
mongoose acts according to definition of user schema. you should add bluepages and image keys to schema of User
Upvotes: 1
Reputation: 138257
Mongoose tricks you out. It adds a toJSON()
and a toString()
method to documents, that only shows the properties defined in the Model. If you log it to the console, toString
will be called, if you send it as json toJSON()
will be called.
console.log(
users[0], // looks as if bluepages does not exist
users[0].bluepages // but it does actually
);
To let the users behave as objects, map them to regular objects:
let users = (await User.find({})).map(u => u.toObject());
Upvotes: 3