简体   繁体   English

在 nodeJS 和 mongoDB 中与 $match 和 $lookup 聚合

[英]aggregate with $match and $lookup in nodeJS and mongoDB

I am hitting http://localhost:4000/api/getsinglepost/6199ae17a515fca1c132c901我正在打 http://localhost:4000/api/getsinglepost/6199ae17a515fca1c132c901

This code give me empty array [] .这段代码给了我空数组[]

When i removed $match give me all posts with "comment_section": []当我删除 $match 时,给我所有带有"comment_section": []

I am uploading post and comment table screenshots as well as the response i need .我正在上传帖子和评论表截图以及我需要的回复

exports.singlePost = async (req, res) => {

      const getit = await postTable.aggregate([
        {
          $match: { _id: req.params.id }
        },
        {
          $lookup:
           {
             from: "commenttables",
             localField: "_id",
             foreignField: "postID",
             as: "comment_section"
           }
        }
      ])
      .then(data => {
        res.send(data);
      }).catch(err => {
        res.status(500).send({
          message: err.message || "something wrong while getting details"
        });
      });
};

My post table:-我的帖子表:-

在此处输入图像描述

My comment table:-我的评论表:-

在此处输入图像描述

Response i need like:-我需要这样的回应:-

在此处输入图像描述

MongoDB query operators are type-sensitive. MongoDB 查询运算符是类型敏感的。 req.param.id most likely contains a string, while the _id fields contain ObjectId , so they don't match. req.param.id很可能包含一个字符串,而_id字段包含ObjectId ,因此它们不匹配。

You can convert the string to ObjectId using the bson module that comes with the mongodb node.js driver.您可以使用 mongodb node.js 驱动程序附带的 bson 模块将字符串转换为 ObjectId。

After requiring the driver要求司机后

const mongo = require("mongodb")

Convert with:转换为:

mongo.ObjectId(req.param.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM