Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - mongoDB (in nodeJS) aggregation pipleine returns empty array

I'm following Jonas Schmeddtman Node.js course and building a tour App. 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.

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;
question from:https://stackoverflow.com/questions/65651552/mongodb-in-nodejs-aggregation-pipleine-returns-empty-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the end of aggregation you should use toArray().Then only aggregated values get instead of getting the aggregationCursor as out.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...