node.js - mongoose 通过嵌套对象 ID 查找返回整个文档

标签 node.js mongodb express mongoose

这是我的文档结构:

{
"_id": "590dc8b17e52f139648b9b94",
"parent": [
    {
        "_id": "590dc8b17e52f139648b9b95",
        "child": [
            {
                "_id": "590dc8b17e52f139648b9b8f"
            },
            {
                "_id": "590dc8b17e52f139648b9b90"
            }
        ]
    },
    {
        "_id": "590dc8c57e52f139648b9b9b",
        "child": [
            {
                "_id": "590dc8c57e52f139648b9b96"
            }
        ]
    }
]}

我试图仅返回有关我正在查找的嵌套对象及其 _id 的信息。

router.get('/child/:id', (req, res) => {
    Project.findOne({ 'parent.child._id': req.params.id },
            (err, results) => {
                    if (err)
                            res.status(500).send(err);
      res.status(200).json(results.parent[0].child.id(req.params.id));

            }
    )});

问题是结果包含整个文档,其中可能包含父级的多个实例 所以显然我的代码只有在已知的 child _id 位于第一个父级中时才有效。

我该如何修复它? 非常感谢

显然,展开和匹配解决方案很好,但对于 Mongoose ,您需要明确说明 id 是 ObjectId 类型。

 {$match:
{ "parent.child._id": new mongoose.Types.ObjectId(id) }
            }

found it here

最佳答案

基本上,您可以先在聚合中 $unwind 父级,然后与子级 id 匹配。这将确保它只为您提供父对象而不是整个文档。此外,如果匹配的 id 不需要位于第一个父对象内,但它可以位于父对象数组内的任何位置。它将从父数组返回 require 对象,该对象在其子数组中包含搜索 id。

db.project.aggregate([ 
    { $unwind : '$parent'},
    { $match : 
        { "parent.child._id" : '590dc8b17e52f139648b9b8f' } 
    } 
]);

蒙古语语法:

//mongoose

let Project = mongoose.model('project', yourProjectSchema);

Project.aggregate([ 
    { "$unwind" : '$parent'},
    { "$match" : 
        { "parent.child._id" : req.params.id } 
    } 
]);

关于node.js - mongoose 通过嵌套对象 ID 查找返回整个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832567/

相关文章:

javascript - 如何在客户端实现 JSON Web token - Node.js

node.js - 在 CentOS 5 服务器上安装 Nodejs 时出错 - 没有模块 bz2

node.js - 从 git 子目录部署到 heroku

node.js - 如何使用相对路径在 Webpack 中使用 SCSS (SASS) 加载 font-awesome?

node.js - 如何从 Controller 中获取配置(从 Controller 中获取配置)?

javascript - Express + PassportJs : Why do we need to delay the execution of method with process. Passport 策略中的 nextTick()?

javascript - Google Cloud Firestore 仅查询时间戳早于 x 的文档

mongodb - mongoDB 中具有时间间隔的增量 MapReduce

mongodb - 仅返回投影数组子文档中的特定字段

java - 当我在现有文档中编辑时,它检索到旧值而不是我的编辑值,我该怎么办?