node.js - 在 MongoDb 和 Mongoose 中按子文档 ID 检索文档
问题描述
在我的一个集合中,每个文档都有子文档,我需要按子文档 ID 检索这些文档。
我的文章架构看起来像这样,
var commentSchema = mongoose.Schema({
userName:{
type: String,
required: true
},
comment:{
type: String,
required: true
}
})
var postSchema = mongoose.Schema({
title:{
type: String,
required: true
},
description:{
type: String,
required: true
},
comments:[commentSchema]
})
我试过这个方法,但它总是返回一个空数组
router.get('/posts/comments/:commentId', function(req, res){
let commentId = req.params.commentId;
Article.find({comments: {_id: commentId}}, function(err, posts){
if(err){
throw err;
}
res.json(posts);
})
});
有没有其他方法可以检索包含特定子文档 ID 的所有文档?
解决方案
推荐阅读
- javascript - 当我点击它外部时无法关闭模式
- jquery - 如果选中第一个复选框,则根据条件禁用其他复选框
- google-app-engine - Flutter w/谷歌云数据存储实现
- vue.js - 动态更改 axios 代理 URL 的正确方法?
- angular - Routerlinkactive选项不起作用angular7
- docker - docker-compose 中的 docker-compose:共享网络
- assembly - MARIE 汇编语言程序。允许用户输入 8 个数字并找到最小和最大作为输出
- python - 使用 qt v=5.9.0 创建 conda env
- docker - 如何在 docker compose 3.7 中指定最大 cpu 和 ram
- android - GridLayout 中的 TextViews 在 Android 右侧被截断