Mongoose 3.6:通过id返回一个子文档

时间:2013-08-23 11:01:35

标签: mongodb mongoose

我有一组线程,每个线程都有一个嵌套的注释文档数组。 我想根据其id返回一个评论文档。 我有线程ID和注释ID。 唉,我似乎无法做到这一点 - 搜索我已经提出以下但我得到一个错误。

  

{[MongoError:不支持的投影选项:$ elemMatch]名称:'MongoError'}

这似乎是一个非常典型的用例,任何人都可以指出我哪里出错了吗?

       var thread_id =  vo.thread_id;
       var _id =  vo._id;
       threads.model.find({_id:thread_id}).select({ comments: { $elemMatch: {_id:_id}}}).exec(function (err, thread) {
                    console.log("***************************************");
                    console.log(err);
                    console.log(thread);
                    done();
                });

1 个答案:

答案 0 :(得分:1)

不幸的是,MongoDB(以及Mongoose)当前并不直接支持该操作。 MongoDB没有能力只返回一个数组元素,所以Mongoose也不支持。 (如果您碰巧拥有数组项的索引,则可以使用slicedocumentation))。

此外,select函数仅包含您要包含/排除的字段列表(documentation)。 select函数映射到MongoDB的projection功能。它不能使用MongoDB运算符。

你可以做select('comments') for example to only include the comments field from the document. But, this would return the entire array of评论。您需要进行客户端过滤以提取您正在寻找的特定评论。

有一个开放式请求,要求添加功能,以便能够从数组here中额外添加特定元素。

有些人可能会建议您尝试聚合框架(here)。