Attempting to modify a mongodb document using the findOneAndUpdate
method.
Experimented with various approaches to locating the document and restructuring the update operation.
router.put(
"/edit",
[
auth,
[
check("name", "Name is required")
.not()
.isEmpty(),
check("email", "Please enter a valid email").isEmail(),
check(
"password",
"Please enter a password with 8 or more characters"
).isLength({ min: 8 })
]
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(404).json({ errors: errors.array() });
}
const { email, password, name } = req.body;
const update = {
email,
password,
name
};
const salt = bcrypt.genSalt(10);
update.password = bcrypt.hash(password, salt);
try {
const user = await User.findOneAndUpdate(
{ user: req.user.id },
{ $set: update },
{ new: true, upsert: true }
);
res.json(user);
} catch (err) {
console.error(err);
res.status(500).send("Server Error");
}
}
);
Desire for the updated user to be returned but consistently encountering an error leading to a 500 response.