Reputation: 143
I am implementing a 'settings' page on my site, through which users can change their email address and password etc. On the settings page, I want to display the email address currently assigned to the user.
router.get("/settings", middleware.isLoggedIn, (req, res) => {
User.find({ "username": req.user.username }, (err, foundUser) => {
if (err) {
console.log("error finding user" + err);
} else {
console.log(foundUser);
var emailAddress = foundUser.email;
res.render("settings", { email: emailAddress });
}
})
})
Simple enough, the console.log prints the user details correctly like so:
[
{
_id: 5e89b7b8a2936f4d3422ffc4,
username: 'cafenero',
email: 'cafe@nero',
__v: 0
}
]
But for some reason, when I tried to use the date in my .ejs file, there variable is not showing!
<label for="email">Email Address</label>
<input type="text" class="form-control" id="email" name="email" value="<%=email%>">
Value is just blank on the page! What am I doing wrong? Thanks!
Upvotes: 0
Views: 406
Reputation: 8125
User.find({
returns array of data. To get the email, you need to access first element than email.
Change var emailAddress = foundUser.email;
to var emailAddress = foundUser[0].email;
console.log(foundUser);
var emailAddress = foundUser[0].email;
res.render("settings", { email: emailAddress });
Or Use findOne
instead of find
User.findOne({ "username": req.user.username }, (err, foundUser) => {
if (err) {
console.log("error finding user" + err);
} else {
console.log(foundUser);
var emailAddress = foundUser.email;
res.render("settings", { email: emailAddress });
}
})
Upvotes: 4