【问题标题】:.map returns an array of empty objects after getting data with Mongoose.map 在使用 Mongoose 获取数据后返回一个空对象数组
【发布时间】:2020-03-23 16:57:39
【问题描述】:

当我想使用 Mongoose 将一组集合返回给我时,我遇到了问题。问题是代码中的 .map 方法返回一个空对象数组,但是如果我将对象单独记录在 .map 中,一切都很好。为什么会这样?

const patients = doctor.patients.map(async patient => {
  try {
    const patientObj = await Patient.findOne({ username: patient });
    patient = patientObj;
    patient.jwt = undefined;
    patient.__v = undefined;
    console.log(patient);  // This works just fine, logs the object the right way

    return patient;
  } catch (err) {
    console.log(err);
  }
});
console.log(patients); // This logs [{}, {}, {}]

【问题讨论】:

  • 1.您的映射函数中没有return。 2. 你传递了一个异步回调,所以不管你有什么代码,你都会得到一个 promise 数组。
  • 您也可以在您的猫鼬模式中添加(选择:false),因此您不必将 patient.password 设置为未定义密码:{type: String, select: false},
  • 此外,您似乎只想要特定医生的患者列表?
  • @Fullhdpixel 是正确的。另外,添加“return”后似乎也不起作用。

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

我猜你想要一组与一位医生相关的患者。试试这个解决方案。

Patient.find({
    username: { $in: doctor.patients }
}, (err: any, patients) => {
    console.log("patients  " + patients)
})

在您的 Patient 模型中添加 (select: false),因此您不必将每个字段都设置为 undefined https://mongoosejs.com/docs/api.html#schematype_SchemaType-select

【讨论】:

猜你喜欢
  • 2013-02-16
  • 2020-09-14
  • 2015-11-25
  • 2019-04-27
  • 2016-07-28
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多