首页 > 解决方案 > 在 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
  });
});

标签: node.jsmongodbmongoose

解决方案


我得到了解决方案

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


推荐阅读