简体   繁体   English

mongoDB(在nodeJS中)聚合管道返回空数组

[英]mongoDB (in nodeJS) aggregation pipleine returns empty array

I'm following Jonas Schmeddtman Node.js course and building a tour App.我正在关注 Jonas Schmeddtman Node.js 课程并构建旅游应用程序。 For some reason, when I send a request using postman on the route upon which this function is called, it returns an empty array instead of the manipulated data.出于某种原因,当我在调用此 function 的路由上使用 postman 发送请求时,它返回一个空数组而不是操作数据。

Below is my complete code.下面是我的完整代码。 Thanks in advance.提前致谢。

      exports.getTourStats=async(req,res)=>
      {
        try
        {
          const stats= await Tour.aggregate([
            {
              $match: { ratingsAverage: { $gte: 4.5 } }
            },
            {
              $group:
              {
                _id: { $toUpper: '$difficulty' },
                      numTours: { $sum: 1 },
                      numRatings: { $sum: '$ratingsQuantity' },
                      avgRating: { $avg: '$ratingsAverage' },
                      avgPrice: { $avg: '$price' },
                      minPrice: { $min: '$price' },
                      maxPrice: { $max: '$price' }
              }
             
            }
          ]);
          
          res.status(200).json(
            {
              status:"success",
              data:
              {
                stats
              }
            });
        }
        catch(error)
        {
          res.status(400).json(
            {
              status:"failed!",
              message:error
            })
        }
      }

//an example document is as below. //示例文档如下。

    "id": 8,
    "name": "The Northern Lights",
    "duration": 3,
    "maxGroupSize": 12,
    "difficulty": "easy",
    "ratingsAverage": 4.9,
    "ratingsQuantity": 33,
    "price": 1497,
    "summary": "Enjoy the Northern Lights in one of the best places in the world",
    "description": "dummy description",
    "imageCover": "tour-9-cover.jpg",
    "images": ["tour-9-1.jpg", "tour-9-2.jpg", "tour-9-3.jpg"],
    "startDates": ["2021-12-16,10:00", "2022-01-16,10:00", "2022-12-12,10:00"]

// schema. // 架构。

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
  },
  duration: {
    type: Number,
    required: [true, 'a tour must have a duaration'],
  },
  maxGroupSize: {
    type: Number,
    required: [true, 'a tour must have a max group size'],
  },
  difficulty: {
    type: String,
    required: [true, 'a tour must have a diffculty'],
  },
  ratingAverage: {
    type: Number,
    default: 4.5,
  },
  ratingQuantity: {
    type: Number,
    default: 0,
  },
  price: {
    type: Number,
    required: [true, 'A tour must have a price'],
  },
  priceDiscount: {
    type: Number,
  },
  summary: {
    type: String,
    trim: true,
    required: [true, 'A tour must have a summary'],
  },
  description: {
    type: String,
    trim: true,
  },
  imageCover: {
    type: String,
    required: [true, 'A tour must have an image cover'],
  },
  images: [String],
  createdAt: {
    type: Date,
    default: Date.now(),
    //to exclude the created at property from response sent back to user we put select property to false.
    select: false,
  },
  startDates: [Date],
});
//creating a model out of the schema we defined.
const Tour = mongoose.model('Tour', tourSchema);
module.exports = Tour;

In the end of aggregation you should use toArray() .Then only aggregated values get instead of getting the aggregationCursor as out.在聚合结束时,您应该使用toArray() 。然后只获取聚合值而不是获取聚合光标。

  exports.getTourStats=async(req,res)=>
  {
    try
    {
      const stats= await Tour.aggregate([
        {
          $match: { ratingsAverage: { $gte: 4.5 } }
        },
        {
          $group:
          {
            _id: { $toUpper: '$difficulty' },
                  numTours: { $sum: 1 },
                  numRatings: { $sum: '$ratingsQuantity' },
                  avgRating: { $avg: '$ratingsAverage' },
                  avgPrice: { $avg: '$price' },
                  minPrice: { $min: '$price' },
                  maxPrice: { $max: '$price' }
          }
         
        }
      ]).toArray()
      
      res.status(200).json(
        {
          status:"success",
          data:
          {
            stats
          }
        });
    }
    catch(error)
    {
      res.status(400).json(
        {
          status:"failed!",
          message:error
        })
    }
  }

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

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