【发布时间】:2020-06-20 19:43:53
【问题描述】:
我有一个名为约会的模型,它有一个名为医生的字段,其类型为 :mongoose.Schema.ObjectId,。我正在尝试对模型执行聚合,并且在第一阶段我正在对医生字段进行 $match 以仅获取与提供的医生 ID 匹配的文档。问题是当我运行查询时我得到一个空数组,但我正在寻找的医生 ID 在数据库中。下面是我的预约模型。现在我不明白为什么当我在医院和医生字段上查询时无法获得结果,但如果在状态字段上进行匹配,我会得到数据。是不是因为医生和医院字段的类型是 type: 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 }
}
);
下面是我的聚合管道
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
});
});
【问题讨论】:
-
Mongoose - SchemaTypes - ObjectId 映射到 ObjectId。您正在尝试使用 string.