'How to properly fetch data from another collection during a API call?
I have a collection called "Appointments", this stores all user appointments, and each appointment stores a storeID that points to an object in a database called "Store" and a userID field that points to the user that created this appointment.
So basically a user creates appointments to a store. In the frontend, when the user clicks on the view appointments option, the appointments are found using the userID, filtered, and returned as a nested object that contains all the user's appointments so far. Say the user has around 4 appointments, all those appointments are returned but only the appointment schema data is returned which only contains the ID of the store the appointment is linked to.
But in the front end, I would like to display the store details for a better user experience. So what I did was I made 2 API calls, the first one to get all appointments, then for each appointment, I would check the storeID and then do separate requests to fetch the store's details from the Store collection.
But doing it this way is very inconsistent and I am creating multiple requests instead of just one. Plus on the front-end, I had to avoid two separate loaders to avoid null errors. I feel like this is not the way to do this and I would like suggestions on the best method to use in this case.
My goal is to finally make one single request, but that one single request should fetch the appointments of the user, for each appointment it has to fetch the store details, such as store name, address, etc, and return both the appointments details and store details as a single object. This way it's just one request and everything will be much smoother, controlled and less error-prone.
Please help me with the best method to do this, as I am unaware of any other method except for fetching separately.
Here is my getAppointment request -> userId is fed using an accessToken, verified and converted, by using the field createdBy;
const getAppointment = async (req, res, next) => {
const appointmentId = req.params.id;
const userId = req.user.userId
const appointment = await Appointment.findOne({ _id: appointmentId, createdBy: userId })
if (!appointment) {
throw new NotFoundError('User does not have any appointments')
}
res.status(StatusCodes.OK).json({ appointment })
}
The following to get the store using store ID:
const getStore = async (req, res, next) => {
try {
const store = await Store.findById(req.params.id);
if (!store) {
throw createError(404, "Store does not exist");
}
const { password, ...info } = store._doc
res.status(200).json(info);
} catch (err) {
if (err instanceof mongoose.CastError) {
next(createError(400, 'Invalid Store ID'))
return;
}
next(err);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
