【问题标题】:Using $match in Moongose Aggretation Pipeline In Mongodb on a field of type: mongoose.Schema.ObjectId在 Mongoose 聚合管道中使用 $match 在 Mongodb 的类型字段上:mongoose.Schema.ObjectId
【发布时间】: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
  });
});

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案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
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2015-05-25
    • 2021-07-21
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多