【问题标题】:Mongoose populate returns empty array but returns data without populateMongoose 填充返回空数组,但返回没有填充的数据
【发布时间】:2017-11-17 03:53:02
【问题描述】:

我正在尝试获取约会并使用用户详细信息和医生详细信息填充它们。我有这样的架构

let appointmentSchema = new Schema({
  reason: String,
  start: DateType,
  end: DateType,
  appointmentStamp: Number,
  userId: {
    type: ObjectId,
    ref: 'User'
  },
  doctorId: {
    type: ObjectId,
    ref: 'Doctor'
  },
  approved: Boolean,
  held: Boolean,
  timeOfAcceptance: Number,
  createdOn: { type: Number, default: (new Date().getTime()) },
  updatedAt: Mixed
}, {runSettersOnQuery: true})

在运行中

Appointment.find({userId: authId}).populate('userId doctorId').exec()

我得到一个空数组 但 Appointment.find({userId: authId}).exec() 使用 find 中提供的 userId 返回该用户的所有约会 我错过了什么

这是一个约会示例

  {
    "_id": "5a0d424079191657fca9e853",
    "reason": "Say Hello",
    "approved": false,
    "held": false,
    "doctor": "5a0add9b577d7916187cd9f2",
    "patient": "59f5df20a3071554c5f843e1",
    "appointmentStamp": 1510927380000,
    "__v": 0,
    "createdOn": 1510817910134
  }

【问题讨论】:

  • 如果您收到一个空结果,这通常意味着引用 ObjectId 值实际上与相关集合中的任何内容都不匹配。显示约会示例以及您认为应该匹配但未返回的 User 和 Doctor 条目。
  • 是的,这就是约会。现在还显示Doctor 和User,它们应该与本文档中的ObjectId 值匹配。您被告知的是,在其_id 字段中存在这些值的文档不存在。还要检查集合名称。 Mongoose 期望它们分别被称为 "doctors" 和 "users"。简而言之,您应该能够做到Doctor.findById("5a0add08577d7916187cd9f1"),如果您无法获得结果,那么这表明您的数据有问题。
  • 我得到了 Doctor.findById('5a0add08577d7916187cd9f1') 的结果

标签: javascript mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

我试过了,效果很好,不知道为什么

patient: {
   type: String,
   ref: 'patient'
},
doctor: {
   type: String,
   ref: 'doctor'
}

我使用 String 类型而不是 ObjectId 那么查询就像

Appointment.find({patient: authId, canceled: false})
  .populate('patient doctor').exec()

【讨论】:

    猜你喜欢
    • 2016-12-04
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2014-11-02
    • 2016-04-28
    • 2017-10-26
    相关资源
    最近更新 更多