작성
·
139
0
userRouter.put('/:userId', async (req, res) => {
try {
const { userId } = req.params;
if (!mongoose.isValidObjectId(userId))
return res.status(400).send({ err: 'invalid userId' });
const { age, name } = req.body;
if (!age && !name)
return res.status(400).send({ err: 'age or name is required' });
if (age && typeof age !== 'number')
return res.status(400).send({ err: 'age must be a number' });
if (name && typeof name.first !== 'string' && typeof name.last !== 'string')
return res.status(400).send({ err: 'first and last name are strings' });
// let updateBody = {};
// if(age) updateBody.age = age;
// if(name) updateBody.name = name;
// const user = await User.findByIdAndUpdate(userId, updateBody, { new: true });
const user = await User.findById(userId);
if (age) user.age = age;
if (name) {
user.name = name;
await Promise.all([
Blog.updateMany({ 'user._id': userId }, { 'user.name': name }),
Blog.updateMany(
{},
{ 'comments.$[comment].userFullName': `${name.first} ${name.last}` },
{ arrayFilters: [{ 'comment.user': userId }] }
),
]);
}
await user.save();
return res.send({ user });
} catch (err) {
console.log(err);
return res.status(500).send({ err: err.message });
}
});