“模型 \"ModelName\" 的路径 \"_id\" 处的值 \"\" 转换为 ObjectId 失败”-Mongoose

sin*_*ngu 0 mongoose mongodb node.js

我正在尝试使用基于我的猫鼬模型的聚合。请调查此问题并帮助我解决错误并给出任何建议。错误:“message”:{“message”:“在模型的路径\“_id \”处,对于值\“tour-stats \”,转换为ObjectId失败\“旅游\””,

路线

router.get('/tour-stats', tour.getTourStats);
Run Code Online (Sandbox Code Playgroud)

控制器

exports.getTourStats = async (req, res) => {
try {
const stats = await Tour.aggregate([
  {
    $match: { ratingsAverage: { $gte: 4.5 } }
  },
  {
    $group: {
      _id: null,
      numTours: { $sum: 1 },
      numRatings: { $sum: '$ratingsQuantity' },
      avgRating: { $avg: '$ratingsAverage' },
      avgPrice: { $avg: '$price' },
      minPrice: { $min: '$price' },
      maxPrice: { $max: '$price' }
    }
  },
  {
    $sort: { avgPrice: 1 }
  }
  // {
  //   $match: { _id: { $ne: 'EASY' } }
  // }
]);

res.status(200).json({
  status: 'success',
  data: {
    stats
  }
});
} catch (err) {
res.status(404).json({
  status: 'fail',
  message: err
});
}
};
Run Code Online (Sandbox Code Playgroud)

旅游模型

const tourSchema = new mongoose.Schema(
{
name: {
  type: String,
  required: [true, 'A tour must have a name'],
  unique: true,
  trim: true,
},
duration: {
  type: Number,
  required: [true, 'A tour must have a duration'],
},
maxGroupSize: {
  type: Number,
  required: [true, 'A tour must  have a group size'],
},
difficulty: {
  type: String,
  required: [true, 'A tour must have a difficulty'],
},
ratingsAverage: {
  type: Number,
  default: 4.5,
},
ratingsQuantity: {
  type: Number,
  default: 0,
},
price: {
  type: Number,
  required: [true, 'A tour must have a price '],
},
priceDiscount: Number,
summary: {
  type: String,
  trim: true,
  required: [true, 'A tour must have a decription'],
},
description: {
  type: String,
  trim: true,
},
imageCover: {
  type: String,
  required: [true, 'A tour must have a cover image'],
},
images: [String],
createdAt: {
  type: Date,
  default: Date.now(),
},
 startDates: [Date],
 }
 // { timestamps: true }
);
Run Code Online (Sandbox Code Playgroud)

样本文件:

{“id”:8,“名称”:“北极光”,“持续时间”:3,“maxGroupSize”:12,“难度”:“简单”,“评级平均”:4.9,“评级数量”:33,“价格": 1497,"摘要":"在世界上最好的地方之一享受北极光","描述":"Sed do eiusmod tempor incididunt ut Labore et dolore magna aliqua, ut enim ad minim veniam, quis nostrud练习 ullamco Laboris nisi ut aliquip ex ea commodo consequat.", "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"] }

提前致谢。

Gre*_*reg 7

我也参加过这门课程,并努力了解发生了什么,终于找到了。就我而言,这是由于路线顺序错误而发生的。

当您尝试将请求发送到“api/v1/tours/tour-stats”时,您实际上将请求发送到“api/v1/tours/:id”,并且“tour-stats”作为此路由的 id(显然无效) ),导致错误。因此,请确保您的“tour-stats”路线在您的 id 路线之前定义。

在此输入图像描述