I would like to update the author name of a post (esc. old posts by that user) anytime that user updates his profile name.
My code looks like this,
router('/:id', async(req, res) {
if (req.body._id == req.params.id) {
try {
const user = await User.find(req.params.id):
let oldfirstName = user.firstname;
let oldlastName = user.lastname;
const author = oldfirstName ' ' oldlastName;
const postsByUser = await Post.find({author: author}); // gets posts by same user
const updatedUser = await User.findByIdAndUpdate(req.params.id, {
{
$set: {
firstname: req.body.firstname,
lastname: req.body.lastname,
}
}
});
let updatedAuthor = updatedUser.firstname ' ' updatedUser.lastname;
await postsByUser.updateMany({}, {author: updatedAuthor});
});
res.status(200).json();
} catch (err) {
res.status(500).json();
}
}
What am I doing wrong please?
I am building a blog. Users full name equals the displayed author name. I tried updating the author's name on old posts anytime there is an update in user's firstname or lastname on profile. I could update user's profile, but the new update does not apply to old posts by that user.
CodePudding user response:
This line seems off to me:
await postsByUser.updateMany({}, {author: updatedAuthor});
postsByUser
is not a Model.
You likely just want to issue an update like this:
await Post.updateMany({author: author}, {$set: {author: updatedAuthor}})
Which is essentially saying "update all posts where author is the "old" author name, and set it to the new author name".