Created
April 14, 2020 20:43
-
-
Save OdongAlican/cbba1feb33c5e1acfcaf1f686bffaa4b to your computer and use it in GitHub Desktop.
updating a post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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