提问者:小点点

在Mongodb中的Moongose聚合管道中对以下类型的字段使用$match:mongoose.schema.objectid


我有一个名为“约会”的模型,它有一个名为“医生”的字段,其类型为:mongoose.schema.objectid,。 我试图在模型上执行聚合,在第一阶段,我在doctor字段上执行$match,以只获取与提供的doctor 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
  });
});

共1个答案

匿名用户

我找到解决办法了

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