首页 > 解决方案 > 在nodejs中使用聚合查询未获取数据

问题描述

我尝试了下面的代码,但只检查并显示了第一个匹配,其他显示为对象,为什么我无法在控制台中看到它。我有 3 位学生学科老师,也为相同的课程制定了架构。尝试聚合

Student.aggregate([

            {

              $match: { name: 'abcd'}
            },

            {
            $lookup:
             {
               from:'teachers',
               pipeline: [{ $match: { name: 'pqrs' } },],
               as: "teacherLookup"

             }
            },
            {
            $lookup:
             {
               from:'subjects',
               pipeline: [{ $match: { name: 'computer' } }],
               as: "subjectLookup"
             }
            }

          ]).then(function (res) {
            console.log(res); 
            res.forEach(function(students){
              let id = students._id;
              console.log(id+ ' got id ')

            }

    output
    student 
    name:'abcd' -- its fetched and other two not displaying values only shows object
    teacherLookup: [ [Object] ]
    subjectLookup: [ [Object] ]

标签: node.jsdatabasemongodbcollectionsaggregation-framework

解决方案


你在那里只是为了投射一些你必须使用$project舞台的东西。

在这里,我添加了查询:

Student.aggregate([
  {
    $match: { name: 'abcd'}
  },
  {
    $lookup:{
       from:'teachers',
       pipeline: [
        { 
          $match: { name: 'pqrs' } 
        },
        {
          $project:{
            "_id":1
          }
        }
       ],
       as: "teacherLookup"
    }
  },
  {
    $lookup:
     {
       from:'subjects',
       pipeline: [
        { 
          $match: { name: 'computer' } 
        },
        {
          $project:{
            "_id":1
          }
        }
       ],
       as: "subjectLookup"
     }
  }
])

有关更多信息,$project请参阅此处

希望这会有所帮助:)


推荐阅读