【发布时间】: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"] }
提前致谢。
【问题讨论】: