【问题标题】:Mongoose 3.6: Returning one subdocument by idMongoose 3.6:按 id 返回一个子文档
【发布时间】:2023-04-09 02:22:01
【问题描述】:

我有一个线程集合,每个线程都有一个嵌套的评论文档数组。 我只想返回一个基于其 ID 的评论文档。 我有线程 ID 和评论 ID。 唉,我似乎做不到 - 搜索我已经想出了以下但我得到一个错误。

{ [MongoError: Unsupported projection option: $elemMatch] name: '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();
                });

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

不幸的是,MongoDB(以及因此 Mongoose)目前不直接支持该操作。 MongoDB 不能只返回数组的一个元素,所以 Mongoose 也不支持。 (如果你碰巧有数组项的索引,你可以使用slice (documentation))。

此外,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 ofcmets`。您需要进行客户端过滤以提取您正在寻找的特定评论。

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

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

【讨论】:

猜你喜欢
  • 2020-01-20
  • 2021-12-26
  • 2020-11-12
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 2020-12-08
  • 2014-11-20
  • 2018-10-01
相关资源
最近更新 更多