Skip to content

Instantly share code, notes, and snippets.

@OdongAlican
Created April 14, 2020 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OdongAlican/cbba1feb33c5e1acfcaf1f686bffaa4b to your computer and use it in GitHub Desktop.
Save OdongAlican/cbba1feb33c5e1acfcaf1f686bffaa4b to your computer and use it in GitHub Desktop.
updating a post
exports.update = function (req, res) {
const newAuthorId = req.params.authorId;
const { postId } = req.params;
const newPost = req.body;
PostModel.findOne({ _id: postId }, (err, post) => {
if (!post) {
return err;
}
const oldAuthorID = post.author._id;
AuthorModel.findById(oldAuthorID)
.then((oldAuthor) => {
if (!oldAuthor) {
return res.status(400).send('No Author with that Particular id');
}
const index = oldAuthor.posts.indexOf(postId);
if (index > -1) {
oldAuthor.posts.splice(index, 1);
}
oldAuthor.save((error, savedAuthor) => {
if (error) {
return error;
}
return savedAuthor;
});
return oldAuthor;
});
AuthorModel.findById(newAuthorId)
.then((newAuthor) => {
if (!newAuthor) {
return err;
}
newAuthor.posts.push(post);
newAuthor.save((error, savedAuthor) => {
if (error) {
return error;
}
return savedAuthor;
});
post.author = newAuthor;
_.merge(post, newPost);
post.save((error, saved) => {
if (error) {
return error;
}
return res.json(saved);
});
return newAuthor;
});
return post;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment