【问题标题】:"Cast to ObjectId failed for value \"\" at path \"_id\" for model \"ModelName\""-Mongoose“模型 \"ModelName\""-Mongoose 的路径 \"_id\" 中的值 \"\" 转换为 ObjectId 失败
【发布时间】:2020-07-28 10:53:13
【问题描述】:

我正在尝试使用基于我的猫鼬模型的聚合。请对此进行调查并帮助我解决错误并提供任何建议。错误:“消息”:{ "message": "对于模型 \"Tour\"" 的路径 \"_id\" 中的值 \"tour-stats\" 转换为 ObjectId 失败,

路线

router.get('/tour-stats', tour.getTourStats);

控制器

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

旅游模型

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

示例文档:

{ “身份证”:8, "name": "北极光", “持续时间”:3, “最大组大小”:12, “困难”:“容易”, “评分平均”:4.9, “评分数量”:33, “价格”:1497, "summary": "在世界上最好的地方之一享受北极光", "description": "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua, ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "imageCover": "tour-9-cover.jpg", “图像”:[“tour-9-1.jpg”,“tour-9-2.jpg”,“tour-9-3.jpg”], "开始日期": ["2021-12-16,10:00", "2022-01-16,10:00", "2022-12-12,10:00"] }

提前致谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我也参加了这门课程,一直在努力理解发生了什么,终于找到了。就我而言,这是因为路线的顺序错误。

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

    【讨论】:

      猜你喜欢
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2020-11-10
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 2021-06-05
      相关资源
      最近更新 更多