首页 > 解决方案 > 在 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 的所有文档?

标签: node.jsmongodbexpressmongoose

解决方案


推荐阅读