mongodb - 是否可以通过 ID 在子数组中找到特定元素并仅编辑该元素?
问题描述
我发现这个答案认为它解决了我的问题,直到我意识到查询返回整个父文档。
无论如何要查询和编辑文档中子数组中的特定元素吗?
所以它会像,
const newComment = {...};
const comment = await Post.find({comments: ObjectId("50ae3bdb50b3d6f014000279")})
comment.push(newComment);
await comment.save();
我想完成这个的原因是因为注释嵌套在Post
模式中。如果我可以返回评论,用评论 ID 指定,并循环浏览所有喜欢的评论,那会更有效率。而不是循环浏览的所有评论Post
,然后循环浏览所有喜欢的东西。
解决方案
您可以使用以下方法,
const newComment = {...};
Post.find( { "comments": "50ae3bdb50b3d6f014000279" } )
.exec((err , foundComment) => {
if(err){
console.log(err)
}else{
foundComment.push(newComment);
foundComment.save();
}
});
推荐阅读
- opencv - 如何从单个组件创建 2D 透视变换矩阵?
- html - 触发:悬停在移动元素上而不移动鼠标
- algorithm - 如何实现 Btree 的迭代器?
- laravel - 在laravel错误中获取除图像之外的所有数据
- python - Python - 无法读取整个 .txt 文件:.readlines 错误?
- c++ - 有什么想法可以像读取代码一样读取用户输入吗?
- c# - AutoCompleteBox 在 CTRL + N 键事件上选择但未聚焦
- javascript - Select2 删除表单中编辑事件的数据
- java - 将 CSV 文件读入二维数组
- spring-mvc - LettuceConnectionFactory 中的错误