0

I have a problem when i want an array of collections returned back to me using Mongoose. The problem is that the .map method in the code returns an array of empty objects, but if I log the objects individually in the .map everything is fine. Why is this happening?

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 [{}, {}, {}]
4
  • 2
    1. You have no return in your mapping function. 2. You pass an async callback so you'd get an array of promises back regardless of what code you have. Commented Mar 22, 2020 at 21:37
  • Also in your mongoose schema you can add (select: false), so you do not have to set patient.password to undefined password: {type: String, select: false}, Commented Mar 22, 2020 at 21:39
  • Moreover, it seems like you just want a list of patients for a specific doctor? Commented Mar 22, 2020 at 21:41
  • @Fullhdpixel that is correct. Also, it doesn't seem to work after adding "return" either. Commented Mar 22, 2020 at 21:42

1 Answer 1

1

I guess you want to have an array of patients which are related to one doctor. Try this solution.

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

In your Patient model add (select: false), so you do not have to set every field to undefined https://mongoosejs.com/docs/api.html#schematype_SchemaType-select

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.