簡體   English   中英

mongoDB(在nodeJS中)聚合管道返回空數組

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

我正在關注 Jonas Schmeddtman Node.js 課程並構建旅游應用程序。 出於某種原因,當我在調用此 function 的路由上使用 postman 發送請求時,它返回一個空數組而不是操作數據。

下面是我的完整代碼。 提前致謝。

      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
            })
        }
      }

//示例文檔如下。

    "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"]

// 架構。

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;

在聚合結束時,您應該使用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