node.js - 在 Mongodb 中的 Moongose 聚合管道中使用 $match 类型的字段:mongoose.Schema.ObjectId
问题描述
我有一个名为约会的模型,它有一个名为医生的字段,其类型为: mongoose.Schema.ObjectId,。我正在尝试对模型执行聚合,并且在第一阶段我正在对医生字段进行 $match 以仅获取与提供的医生 ID 匹配的文档。问题是当我运行查询时我得到一个空数组,但我正在寻找的医生 ID 在数据库中。下面是我的预约模型。现在我不明白为什么当我在医院和医生字段上查询时我无法获得结果,但如果在状态字段上进行匹配我得到数据。是不是因为医生和医院字段的类型 为: mongoose.Schema.ObjectId。请帮忙
const appointmentSchema = new mongoose.Schema(
{
patient: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'Patient user id must be provided'
},
hospital: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'Hopital is reqired'
},
doctor: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'Doctor is require'
},
status: {
type: String,
default: 'Active',
trim: true,
enum: {
values: ['Active', 'Inactive'],
message: 'Wrong Status Supplied'
}
},
startDate: {
type: Date,
required: true
},
endDate: {
type: Date
},
completed: {
type: Boolean,
default: false
},
message: String,
createdAt: {
type: Date,
default: Date.now()
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
下面是我的聚合 ppipeline
exports.doctorSchedlue = catchAsync(async (req, res, next) => {
const aggregateData = await Appointment.aggregate([
{ $match: { doctor: '5ee9be0147faee607cb3cea8' } }
]);
res.status(200).json({
status: 'success',
id: req.params.id,
aggregateData
});
});
解决方案
我得到了解决方案
exports.doctorSchedlue = catchAsync(async (req, res, next) => {
const doctAppointments = await Appointment.find({ doctor: req.params.id });
const aggregateData = await Appointment.aggregate([
{
$match: { doctor: new ObjectId('5ee9be0147faee607cb3cea8') }
}
]);
res.status(200).json({
status: 'success',
id: req.params.id,
aggregateData,
doctAppointments
});
});
推荐阅读
- dataframe - Joining Multiple Data Frames
- java - RotateTransition 导致 GUI 在 javaFX 中冻结
- typescript - 如何在 TypeScript 中模拟私有和公共构造函数重载
- amazon-ecs - 连接到 MSK 时 ECS 超时的 kafka-connect
- python - 如何在 Python 中使用变量作为数组索引?
- google-sheets-api - 更改 Google Sheets API 配额是否需要付费?
- css - 我的 CSS 覆盖了 React 中的引导表
- javascript - 如何向 addEventListener 添加另一个函数
- pine-script - Tradingview按条件删除行
- asp.net-mvc - 如何解决 MVC 5 更新和删除错误