After researching various SO posts, I have come across different methods to achieve this task. Hence, I am curious to know which approach is considered the most preferable. Since I am instructing students, it is important for me to teach them best practices.
If we consider the following BlogPost
object (Simplified):
var BlogPostSchema = new mongoose.Schema({
body: String,
comments: [String]
});
and the goal is to add a new comment to the array of comments for this blog, I can think of at least 3 main ways to accomplish this:
1) In Angular, push the comment to the blog object and then submit a PUT
request to the /blogs/:blogID
endpoint to update the entire blog object with the new comment included.
2) Make a POST
request to a /blogs/:blogID/comments
endpoint where the request body solely consists of the new comment. Retrieve the blog, push the comment to the array using vanilla JS, and save it:
BlogPost.findById(req.params.blogID, function(err, blogPost) {
blogPost.comments.push(req.body);
blogPost.save(function(err) {
if (err) return res.status(500).send(err);
res.send(blogPost);
});
});
OR
3) Send a POST
to a /blogs/:blogID/comments
endpoint with the new comment in the request body, and then utilize MongoDB's $push
or $addToSet
to add the comment to the array:
BlogPost.findByIdAndUpdate(
req.params.blogID,
{$push: {comments: req.body}},
{safe: true, new: true},
function(err, blogPost) {
if (err) return res.status(500).send(err);
res.send(blogPost);
});
});
I came across a helpful StackOverflow post, where a user discusses the pros and cons of option 2 versus option 3, suggesting that option 2 is simpler and recommended whenever possible. (Also, avoiding methods that may limit the use of hooks and other mongoose features.)
What are your thoughts on this? Any advice you would like to share?