[英]Pushing new item to a mongoDB document array
I've looked through a bunch of other SO posts and have found different ways to do this, so I'm wondering which is most preferred. 我浏览了许多其他的SO帖子,并找到了不同的方法来执行此操作,所以我想知道哪个是最优选的。 I'm teaching this to students, so I want to give them best practices. 我正在教学生,所以我想给他们最佳实践。
If I have the following BlogPost
object (Simplified): 如果我有以下BlogPost
对象(简体):
var BlogPostSchema = new mongoose.Schema({
body: String,
comments: [String]
});
and I want 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) Push the comment to the blog object in Angular and submit a PUT
request to the /blogs/:blogID
endpoint, updating the whole blog object with the new comment included. 1)将注释推送到Angular中的博客对象,然后向/blogs/:blogID
端点提交PUT
请求,并使用新的注释更新整个博客对象。
2) Submit a POST
request to a /blogs/:blogID/comments
endpoint where the request body is just the new comment, find the blog, push the comment to the array in vanilla js, and save it: 2)将POST
请求提交到/blogs/:blogID/comments
端点,其中请求主体只是新注释,找到博客,将注释推送到vanilla js中的数组,然后保存:
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) Submit the POST
to a /blogs/:blogID/comments
endpoint with the request body of the new comment, then use MongoDB's $push
or $addToSet
to add the commend to the array of comments: 3)使用新注释的请求正文将POST
提交到/blogs/:blogID/comments
端点,然后使用MongoDB的$push
或$addToSet
将注释添加到注释数组:
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 did find this stackoverflow post where the answerer talks about option 2 vs. option 3 and basically says to use option 2 whenever you can, which does seem simpler to me. 我确实找到了这个stackoverflow帖子 ,回答者在其中讨论了选项2与选项3,并且基本上说要尽可能使用选项2,这对我来说似乎更简单。 (And I usually try to avoid methods that stop me from being able to use hooks and other mongoose goodies.) (而且我通常会尝试避免使我无法使用钩子和其他猫鼬礼物的方法。)
What do you think? 你怎么看? Any advice? 有什么建议吗?
From application point of view, point 3 is better. 从应用的角度来看,第3点更好。 The reason I think are. 我认为是这样。
Performance wise they both do the same thing, so there might not be much or any visible difference. 在性能方面,它们都做相同的事情,因此可能没有太多差异或任何明显的差异。 But option 3 is bit safer and cleaner. 但是选项3更安全,更清洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.