Решение состоит в следующем:
Прежде чем мне просто нужно найти _id: id, таким образом, и так как поля выше пусты, приложение вернет ту же страницу с заполненными полями .
router.post("/profileEdit/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
let errors = [];
if (!req.body.firstName) {
errors.push({ text: "Please add your first name" });
}
if (!req.body.lastName) {
errors.push({ text: "Please add your last name" });
}
if (!req.body.username) {
errors.push({ text: "Please add your username" });
}
if (!req.body.email) {
errors.push({ text: "Please add you email" });
}
if (errors.length > 0) {
User.find(
{ _id: id },
{
firstName: 1,
lastName: 1,
username: 1,
email: 1,
password: 1,
_id: { $elemMatch: { _id: id } },
date: 1
}
).then(user => {
res.render("users/profileEdit", {
user: user
});
});
} else {
User.updateOne(
{ _id: id },
{
$set: {
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
email: req.body.email
}
}
).then(user => {
req.flash("success_msg", "Profile Updated");
res.redirect("/users/profile/" + id);
});
}
});