Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

I tried to store the doctor details in array and display appointment and doctor Name Value response. Appointment value is achieved but doctor Name Value comes empty even if it shows in console.

// get specific appointments of user

router.get("/user/:userId", async (req, res) => {

    try {

        console.log("user_id", req.params.userId);

        const user = await User.findById(req.params.userId);

        console.log("user", user);

        const uservalue = user._id;

        console.log("user_value", uservalue);

        const appointment = await Appointment.find({

            user_id: uservalue

        });

        console.log("appointments", appointment);

        const doctorNameValue = [];

        appointment.forEach(async element => {

            const doctor = element.doctor_id;

            const doctorDetails = await Doctor.findById({

                _id: doctor

            });

            doctorNameValue.push(doctorDetails);

            console.log(doctorNameValue);

        });

        res.json({

            appointments: appointment,

            doctorNameValue

        });

    } catch (err) {

        res.status(401).json({

            message: err

        });

    }

});

1 Answer

0 votes
by (25.1k points)

The issue is happening because you are sending the request within the forEach loop, you need to send the request after the forEach loop, like this:

var count = 0;

appointment.forEach(async element => {

            const doctor = element.doctor_id;

            const doctorDetails = await Doctor.findById({

                _id: doctor

            });

            count++;

            doctorNameValue.push(doctorDetails);

            console.log(doctorNameValue);

            if(count == appointment.length){

               res.json({

               appointments: appointment,

               doctorNameValue

               });

            }    

        });

Browse Categories

...